简体   繁体   English

javascript数组在函数外空

[英]javascript array empty outside a function

I have JavaScript code like this: 我有这样的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

two logs with different result, what am I doing wrong? 两个日志结果不同,我做错了什么? thanks for pointers. 谢谢指点。

Ajax is asynchronous. Ajax是异步的。 That means that console.log(buffer) at the end is executed before the response from the Ajax request. 这意味着最终的console.log(缓冲区)在Ajax请求的响应之前执行。

You should change your method to this: 您应该将方法更改为:

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);
});

You are trying to log() the buffer before the AJAX request in executed. 您正在尝试在执行AJAX请求之前log()缓冲区log() To solve this, your fetchData function needs to handle a callback function. 要解决此问题,您的fetchData函数需要处理callback函数。

var buffer=new Array();

function fetchData(min,max, callback){
    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
            if(typeof callback == 'function'){
                callback.call(this);
            }
        } 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(buffer);
});

This is the most basic implementation, and will work only if the AJAX response is successful. 这是最基本的实现,仅在AJAX响应成功时才有效。

This is asynchronous. 这是异步的。 So your flow goes like this: 所以你的流程是这样的:

  1. call fetchData() 调用fetchData()
  2. ajax request is sent, registering an onreadystatechange callback 发送ajax请求,注册onreadystatechange回调
  3. fetchData() completes and returns fetchData()完成并返回
  4. buffer is logged out, which doesn't yet contain anything. 注销buffer ,但尚未包含任何内容。
  5. Sometime later, the ajax request completes and triggers the callback 稍后,ajax请求完成并触发回调
  6. The callback puts things in the array. 回调将事物放入数组中。
  7. buffer get's logged out from the callback, and you see it now has items in it. buffer get从回调中注销,你看到它现在有条件。

So you are only starting the asynchronous request once you hit that first console.log. 因此,只有在第一次访问console.log时才启动异步请求。 But it actually finishes long afterward. 但它实际上很久以后就结束了。

A couple of issues here. 这里有几个问题。 When the ajax call completes the 2nd console.log has already executed before the variable was set. 当ajax调用完成后,第二个console.log已在变量设置之前执行。

Also,You're not using the buffer varaible as an Array . 此外,您没有使用buffer变量作为Array

Seems right to me. 似乎对我来说。 buffer is empty to start and it doesn't get set until AFTER the asynchronous call is made, so even though you're fetchingData before the second console.log, you're not receiving it until after it shows an empty buffer. 在启动异步调用之后,buffer才会启动并且它不会被设置,所以即使你在第二个console.log之前获取Data,你也不会在它显示空缓冲区之前收到它。

MDN: https://developer.mozilla.org/en/XMLHttpRequest MDN: https//developer.mozilla.org/en/XMLHttpRequest

void   open(in AUTF8String method, in AUTF8String url, in boolean async, in AString user, in AString password);

The third argument is used to tell the browser whether the request should be made asynchronous or not. 第三个参数用于告诉浏览器是否应该使请求异步。 You set it to true, thus it will be async. 您将其设置为true,因此它将是异步的。 Async basically means that the request is sent and meanwhile other code is executed. 异步基本上意味着发送请求,同时执行其他代码。 So, it starts the request, and while waiting for a response, it logs the buffer: before the request has finished. 因此,它启动请求,在等待响应时,它会在请求完成之前记录缓冲区: If you want to log the contents, do it in the onreadystatechange event or set the third argument (async) to false. 如果要记录内容,请在onreadystatechange事件中执行此操作,或将第三个参数(async)设置为false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM