AJAX - 如何确定收到所有数据?

时间:2016-10-05 00:01:41

标签: javascript ajax

后台:我正在尝试使用AJAX检索数据,并将其分配给变量。我试图将AJAX请求设置为同步,但Firefox不允许它。

问题:如何确定收到所有数据?

function search(){
    var data = [];
    this.init = function(){
        data = getData({"url":"/imglib/Inventory/cache/2335/VehInv.js"});
        console.log(data);  // Returns as 'undefined'. Possibly because of asynchronous call?
    };
    var d = new Date();
    function getData(url){
        var xhttp: new XMLHttpRequest();
        var dataURL = url + '?v=' String(d.getTime());
        xhttp.onreadystatechange = function(){
            if(this.readyState = 4 && this.status == 200){
                var r = this.responseText;
                var s = r.indexOf('[') + 1;
                var e = r.indexOf(']');
                var jsonData = JSON.parse("[" + r.slice(s,e) + "]");
                return jsonData;
            }
        };
        xhttp.open("GET", dataURL, true);
        xhttp.send();
    }
};

2 个答案:

答案 0 :(得分:0)

在使用异步内容时必须使用回调..

function search(){
    this.init = function(){
        getData("http://www.petesrvvt.com/imglib/Inventory/cache/2335/VehInv.js", function(data){
            console.log(data);  // Returns as 'undefined'. Possibly because of asynchronous call?
        });
    };
    var d = new Date();
    function getData(url, callback){
        var xhttp: new XMLHttpRequest();
        var dataURL = url + '?v=' String(d.getTime());
        xhttp.onreadystatechange = function(){
            if(this.readyState = 4 && this.status == 200){
                var r = this.responseText;
                var s = r.indexOf('[') + 1;
                var e = r.indexOf(']');
                var jsonData = JSON.parse("[" + r.slice(s,e) + "]");
                callback(jsonData);
            }
        };
        xhttp.open("GET", dataURL, true);
        xhttp.send();
    }
};

答案 1 :(得分:0)

调用将处理" onreadystatechange"上调用的函数中的数据的函数。它不起作用的原因是变量"数据"在尝试使用异步查询时,不会使用异步查询的结果定义。



(function search() {
  var data = [];
  this.init = function() {
    data = getData({
      "url": "http://www.petesrvvt.com/imglib/Inventory/cache/2335/VehInv.js"
    });
    // This is definitely caused by the asynchronous XMLHttpRequest  
    //console.log(data); // This needs to be moved to the callback that is invoked when the request completes. See below
  };
  var d = new Date();

  function getData(url) {
    var xhttp: new XMLHttpRequest();
    var dataURL = url + '?v='
    String(d.getTime());
    xhttp.onreadystatechange = function() {
      if (this.readyState = 4 && this.status == 200) {
        var r = this.responseText;
        var s = r.indexOf('[') + 1;
        var e = r.indexOf(']');
        var jsonData = JSON.parse("[" + r.slice(s, e) + "]");
        // This is how you be sure you get your data
        console.log(jsonData);
      }
    };
    xhttp.open("GET", dataURL, true);
    xhttp.send();
  }
})();