我使用以下标准 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!因此,让我们将我的异步更改为 true。噢,现在我收到这个错误了。
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
事实并非如此,它们不会导致任何等待发生。他们只需检查值然后继续。每当发生变化时,回调本身就会被调用,这并不一定意味着它已经完成。在回调内部,这些条件用于检查请求是否已成功完成。
关于javascript - 仅使用异步 XHR 请求解析 JSON 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46187361/