我知道这个问题已在这里多次提出,但我无法弄清楚我的代码的错误。我收到此错误' Uncaught SyntaxError:意外的令牌o'
这是我的ajax代码:
require
这是我的函数,它将解析返回的数据:
$.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");
}
});
这是我从网络服务返回的JSON数据:
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;
}
答案 0 :(得分:1)
var arr = JSON && JSON.parse(response) || $.parseJSON(response);
在填充response
之前已经解析了JSON。
(jQuery将在两种情况下执行此操作:如果指定dataType: 'json'
(您执行此操作)或未指定dataType且服务器表示响应为JSON(它应该))。
您(隐式地)将其转换为字符串("[object Object]"
)并尝试将解析为作为JSON(它不是)。
删除该行。
答案 1 :(得分:1)
您的JSON数据无效,您在,
和}
之间缺少逗号({
)。
修正:
'[{
"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"
}]'