bob.mazzo
bob.mazzo

Reputation: 5637

How to read a Json file in jQuery

I'm using VS2012, and running an ASP.NET MVC4 project.

I cannot seem to get this to fire below :

$.ajax({
    url: "~/xml/JsonTest.json",
    type: "GET",
    dataType: "json",
    success: function (json) {
        alert("HI");                
    }
}); 

I also tried it this way , but to no avail :

$.getJSON('../xml/JsonTest.json', function (json) {            
        alert("GET JSON !");
    });

Is it somehow not finding the directory structure ? thanks. Bob

Upvotes: 0

Views: 214

Answers (2)

bob.mazzo
bob.mazzo

Reputation: 5637

Best solution for my case was to properly code it up in a C# method as follows :

   public string getJsonParameters()
    {

        JavaScriptSerializer ser = new JavaScriptSerializer();

        string jsonStr = System.IO.File.ReadAllText(Server.MapPath("~/App_Data/myKeys.json"));                        

        JsonParameters jsonData = (JsonParameters)ser.Deserialize(jsonStr, typeof(JsonParameters));            

        return  jsonStr;
    }

Upvotes: 0

David
David

Reputation: 219057

The first one definitely won't work, since ~ doesn't mean anything client-side. What actual URL is requested by the second example? Does it send an AJAX request at all? What is the response?

If you have a dynamic server-side URL then you'll want to use server-side code to dynamically build it in the rendered output. Something like this:

$.ajax({
    url: '@Url.Content("~/xml/JsonTest.json")',
    type: 'GET',
    dataType: 'json',
    success: function (json) {
        alert("HI");                
    }
});

This would result in the client-side JavaScript being rendered with the full URL for the server-side path "~/xml/JsonTest.json".

Upvotes: 2

Related Questions