我有这样的JavaScript代码:

var buffer=new Array();

function fetchData(min,max){
    var ajaxReq = new XMLHttpRequest();
    ajaxReq.onreadystatechange = function(){
    if (ajaxReq.readyState === 4) {
        if (ajaxReq.status === 200) {
            buffer= ajaxReq.responseText;
            console.log(buffer)//this logs an array to console
        } else {
            console.log("Error", ajaxReq.statusText);
        }
    }
    };
    ajaxReq.open('GET', "server/controller.php?min="+min+"&max="+max, true);
    ajaxReq.send();
}

fetchData(1,100);
console.log(buffer);//this log an empty array

两个结果不同的日志,我在做什么错?感谢您的指导。

最佳答案

Ajax是异步的。这意味着最后的console.log(buffer)在Ajax请求的响应之前执行。

您应该将方法更改为此:

function fetchData(min,max,callback){
  var ajaxReq = new XMLHttpRequest();
  ajaxReq.onreadystatechange = function(){
    if (ajaxReq.readyState === 4) {
      if (ajaxReq.status === 200) {
        buffer= ajaxReq.responseText;
        callback();
        //console.log(buffer)//this logs an array to console
      } else {
        console.log("Error", ajaxReq.statusText);
      }
     }
  };
  ajaxReq.open('GET', "server/controller.php?min="+min+"&max="+max, true);
  ajaxReq.send();
}

fetchData(1,100,function(){
    console.log("My Ajax request has successfully returned.");
    console.log(buffer);
});

10-08 11:51