错误解析JSON只能用异步XHR请求
问题描述:
我现在用的是如下因素的标准XHR请求错误解析JSON只能用异步XHR请求
//retrieve markerData from JSON
function retrieveMarkers(){
var markersXMLhttp = new XMLHttpRequest();
//open the request and store parameters for the request. GET (or POST) is method to send,
//the pathway or url of the data is specified, and whether or not the request is asynchronous
markersXMLhttp.open("GET", "../../map/json/myMapMarker.json", false);
//send the request
markersXMLhttp.send();
//there conditions allow the request to wait until the server respondes that it is ready.
if(markersXMLhttp.readyState == 4 && markersXMLhttp.status == 200){
//the response is stored in a variable
var XMLmarkersResult = markersXMLhttp.responseText;
}
//convert JSON string to javascript object
var markersResult = JSON.parse(XMLmarkersResult);
return markersResult;
}
我有异步设置为false,所以我得到了以下错误拉标记物体关闭数据库的
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience.
我同意Mozilla!所以让我们将Asynch改为真。 O快照,现在我得到这个错误。
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
这到底是怎么回事,我的JSON文件没有任何不同。异步处理json的方式不同吗?我喜欢解决这个问题,以免我的请求中出现任何错误。以下我会发布我的JSON代码样本,以防问题出在那里。
{
"myMarkers" : [
{
"index" : "000",
"position" : {
"lat" : 45.5,
"lng" : -122.61
},
"description" : "Portland OR",
"infoWindow" : "The origin of the journey, where my roots are, and were many great people live"
},
{
"index" : "001",
"position" : {
"lat" : 44.5,
"lng" : -121.61
},
"description" : "A New Place",
"infoWindow" : "The duplicat will carry for the replicons... until the safe find the fires of the fury"
}
]
}
答
异步表示请求在您的代码继续运行时发生在后台。您将使用onreadystatechange
的回叫等待被通知请求已完成,以便您可以处理响应。
markersXMLhttp.onreadystatechange = function() {
// Check the readyState and status in here, then process the
// response if they're 4 and 200 respectively
};
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
代码包含如下评论(我已经稍微改动过):
// these conditions allow the request to wait
这是不正确的,他们不造成任何等待发生。他们只是检查值,然后继续。回调本身只要有变化就被调用,这并不一定意味着它完成了。在回调内部,这些条件用于检查请求是否已成功完成。
答
当使用异步请求时,脚本在请求发生时继续执行。所以,当你尝试运行JSON.parse()时,你的JSON并没有被返回。
为了解决这个问题。你必须定义一个回调方法,并把它分配给了XMLHttpRequest的“的onload”属性...
如果这是您正在使用异步请求第一次回调和比起这件事,起初可能有点“令人难以置信”。我建议你阅读一下这个话题,并看看很多例子。
您将需要从根本上调整您的思维/设计,以使您的代码不再“从上到下”运行。
感谢您对答案的解释。我试图理解代码背后的机制和推理,这无疑帮助我看到发生了什么。 – DMrFrost