gpt4 book ai didi

javascript - 未捕获的语法错误 : Unexpected token o - JSON. 解析

转载 作者:行者123 更新时间:2023-12-02 16:14:27 25 4
gpt4 key购买 nike

我知道这个问题已经在这里多次提出,但我无法找出我的代码的错误。我收到此错误“Uncaught SyntaxError: Unexpected token o”

这是我的 ajax 代码:

$.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");
}
});

这是我的函数,它将解析返回的数据:

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;
}

这是我从网络服务返回的 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"
}]'

最佳答案

 var arr = JSON && JSON.parse(response) || $.parseJSON(response);

在填充 response 之前,JSON 已被解析。

(jQuery 将在两种情况下执行此操作:如果您指定 dataType: 'json' (您这样做)或者如果您未指定 dataType 并且服务器说响应是 JSON (它应该))。

您正在(隐式)将其转换为字符串(“[object Object]”)并尝试将解析为 JSON(事实并非如此)。

删除该行。

关于javascript - 未捕获的语法错误 : Unexpected token o - JSON. 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29829128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com