The following JSON is what I am sending back to my jQuery script from the server.
{"items": [
{ "id": "116", "first_name": "Sean", "last_name": "borsen" },
{ "id": "871", "first_name": "Sergio", "last_name": "spake" },
{ "id": "1337", "first_name": "SethTest", "last_name": "Test" }
],
"message": "success"
}
I intend to use this object to build an html table. When I return this type of JSON though, I get either of the following 2 errors in Chrome:
Uncaught SyntaxError: Unexpected token ‘,’
or this error
Uncaught SyntaxError: Unexpected token ‘:’
Here is my AJAX post code
$.ajax({
url: "ClientEmarGroup.aspx",
datatype: 'json',
data: eval('(' + d + ')'),
success: bindData
});
Here is the line I get the error on in my bindData function:
bindData = function (data) {
var $d = eval("(" + data + ")");
Further, I get the script to work if I format my JSON items like so:
{"items": [
{ "id": "116", "name": "Sean borsen" },
{ "id": "871", "name": "Sergio spake" },
],
"message": "success"
}
But thats not what I want.
So my question is, what is wrong with my JSON string formatting that is preventing me from sending a complex object back to jQuery?
How do I format my JSON to return an array of items that have more than 2 properties?
You have spelled the proeprty
dataTypewrong, note the capital T.This causes jQuery to try to find out by itself what the data type is, and if you don’t serve the JSON with the correct content type, it will try to parse it as something else, like XML.
If jQuery manages to guess the data type correctly, it will parse the string to an object before calling the success function, so you should not parse the data again.
Note: If you need to parse JSON, you should note the
evalfunction, you should use the$.parseJSONmethod.