Reputation: 11
I know that this problem has been raised here many times, but i cant figure out the error of my code. I'm getting this error 'Uncaught SyntaxError: Unexpected token o'
Here's my ajax code:
$.ajax({
type: "POST",
url: "json-http-server.aspx/GetDoctors",
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: myFunction,
failure: function (response) {
alert("AJAX error");
}
});
Here's my function that will parse the data returned:
function myFunction(response) {
var arr = JSON && JSON.parse(response) || $.parseJSON(response);
var out = "";
out += "<table border='1'>";
out += "<tr><th>Title</th>";
out += "<th>Name</th>";
out += "<th>Gender</th>";
out += "<th>Address</th>";
out += "<th>Hospital</th></tr>";
for (var i = 0; i < arr.length; i++) {
out += "<tr>";
out += "<td>";
out += arr[i].Title;
out += "</td>";
out += "<td>";
out += arr[i].Name;
out += "</td>";
out += "<td>";
out += arr[i].Gender;
out += "</td>";
out += "<td>";
out += arr[i].Address;
out += "</td>";
out += "<td>";
out += arr[i].Hospital;
out += "</td>";
out += "</tr>";
}
out += "</table>";
document.getElementById("OutputDiv").innerHTML = out;
}
Here's is my JSON data returned from a webservice:
'[{
"Title":"Univ. Prof. Dr.",
"Name":"John",
"Gender":"Doe",
"Address":"Washington DC, USA",
"Hospital":"Washington General Hospital"
}
{
"Title":"Univ. Prof. Dr.",
"Name":"Billy",
"Gender":"Joe",
"Address":"California, USA",
"Hospital":"AKH Univ-Kl.f.Innere Med. II"
}
{
"Title":"Univ. Prof. Dr.",
"Name":"Alex",
"Gender":"Haize",
"Address":"Michigan, 2500, USA",
"Hospital":"Rheuma-SKA Baden der SVA der gew. Wirtschaft"
}]'
Upvotes: 0
Views: 826
Reputation: 23830
Your JSON data is invalid, you're missing commas (,
) between }
and {
.
Fixed:
'[{
"Title":"Univ. Prof. Dr.",
"Name":"John",
"Gender":"Doe",
"Address":"Washington DC, USA",
"Hospital":"Washington General Hospital"
},
{
"Title":"Univ. Prof. Dr.",
"Name":"Billy",
"Gender":"Joe",
"Address":"California, USA",
"Hospital":"AKH Univ-Kl.f.Innere Med. II"
},
{
"Title":"Univ. Prof. Dr.",
"Name":"Alex",
"Gender":"Haize",
"Address":"Michigan, 2500, USA",
"Hospital":"Rheuma-SKA Baden der SVA der gew. Wirtschaft"
}]'
Upvotes: 1
Reputation: 943108
var arr = JSON && JSON.parse(response) || $.parseJSON(response);
The JSON has already been parsed before response
was populated.
(jQuery will do this under two circumstances: If you specify dataType: 'json'
(which you do) or if you don't specify a dataType and the server says that the response is JSON (which it should)).
You are (implicitly) converting it to a string ("[object Object]"
) and trying to parse that as JSON (which it isn't).
Remove that line.
Upvotes: 1