I'm having difficulty parsing some JSON data returned from my server using jQuery.ajax()
To perform the AJAX I'm using:
$.ajax({ url: myUrl, cache: false, dataType: "json", success: function(data){ ... }, error: function(e, xhr){ ... } });
And if I return an array of items then it works fine:
[ { title: "One", key: "1" }, { title: "Two", key: "2" } ]
The success function is called and receives the correct object.
However, when I'm trying to return a single object:
{ title: "One", key: "1" }
The error function is called and xhr contains 'parsererror'. I've tried wrapping the JSON in parenthesis on the server before sending it down the wire, but it makes no difference. Yet if I paste the content into a string in Javascript and then use the eval() function, it evaluates it perfectly.
Any ideas what I'm doing wrong?
Anthony
According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page. Many developers use JSON to pass AJAX updates between the client and the server.
jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!
Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.
Is your server sending data as Content-Type "*/json"
? If not, modify the response headers accordingly. Sending "application/json"
would be fine, for example.
According to the json.org specification, your return is invalid. The names are always quoted, so you should be returning
{ "title": "One", "key": "1" }
and
[ { "title": "One", "key": "1" }, { "title": "Two", "key": "2" } ]
This may not be the problem with your setup, since you say one of them works now, but it should be fixed for correctness in case you need to switch to another JSON parser in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With