仅使用异步XHR请求解析JSON时出错

时间:2017-09-13 01:08:46

标签: javascript json asynchronous xmlhttprequest

我使用下面的标准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;                                                           
    }                     

我将Asynchronous设置为false,因此出现以下错误

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience.

我同意Mozilla!所以让我的Asynch改为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"
      }                                                                                     
    ]                                                                                       
  } 

2 个答案:

答案 0 :(得分:1)

异步意味着在代码继续运行时请求在后台发生。您将使用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

事实并非如此,它们不会导致任何等待。他们只需检查值然后继续。每当某些内容发生变化时,都会调用回调本身,这并不一定意味着它已完成。在回调中,这些条件用于检查请求是否已成功完成。

答案 1 :(得分:1)

使用异步请求时,脚本会在请求发生时继续执行。因此,当您尝试在其上运行JSON.parse()时,您的JSON尚未返回。

为了处理这个问题。您必须定义一个回调方法并将其分配给XMLHttpRequest的'onload'属性...

function retrieveMarkers(callbackFunction){
  var markersXMLhttp = new XMLHttpRequest();

  // This gets called once the request is complete.
  markersXMLhttp.onload = function() {
    if(markersXMLhttp.readyState == 4){
      // Parse the JSON and call the function passed in as a parameter.
      callbackFunction(JSON.parse(markersXMLhttp.responseText));
    }
  };

  markersXMLhttp.open("GET", "../../map/json/myMapMarker.json", false);
  markersXMLhttp.send();
}

// Elsewhere in your code call your method and pass in a function....
retrieveMarkers((markers) => {
  // Do some work with your markers here...
  console.log(markers);
});

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

如果这是您第一次使用异步请求,那么回拨等等可能会让您感到有些“令人难以置信”。我建议你阅读有关该主题的内容并查看大量示例。

您需要从根本上调整您的思维/设计,使您的代码不再“从上到下”运行。