将 XMLHttpRequest.responseText 存储到变量中

Storing XMLHttpRequest.responseText into variable

本文关键字:变量 存储 XMLHttpRequest responseText      更新时间:2023-09-26

不太熟悉XMLHttpRequest,但我在Google Chrome扩展中使用了跨源功能。这很好用(我可以确认我得到了我需要的适当数据),但我似乎无法将其存储在"响应"变量中。

我将不胜感激任何帮助。

function getSource() {
    var response;
    var xmlhttp;
    xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
             response = xmlhttp.responseText;
                 //IM CORRECTLY SET HERE
        }
        //I'M ALSO STILL WELL SET HERE
    }
    //ALL OF A SUDDEN I'M UNDEFINED.
    xmlhttp.open("GET","http://www.google.com",true);
    xmlhttp.send();
    return response; 
}

onreadystatechange函数是异步的,也就是说,在函数完成之前,它不会阻止后面的代码运行。

出于这个原因,你完全错误地这样做。 通常在异步代码中,回调用于能够在onreadystatechange事件触发时准确调用,以便您知道当时能够检索响应文本。 例如,这将是异步回调的情况:

function getSource(callback) {
    var response, xmlhttp;
    xmlhttp = new XMLHttpRequest;
    xmlhttp.onreadystatechange = function () {
      if (xmlhttp.readyState === 4 && xmlhttp.status === 200 && callback) callback(xmlhttp.responseText);
    }
    xmlhttp.open("GET", "http://www.google.com", true);
    xmlhttp.send();
}

把它想象成使用 setTimeout ,这也是异步的。 下面的代码在结束之前不会挂起 100 000 000 000 000 秒,而是立即结束,然后等待计时器启动以运行函数。 但到那时,赋值是无用的,因为它不是全局的,作业范围内没有其他任何东西。

function test()
{   var a;
    setTimeout(function () { a = 1; }, 100000000000000000); //high number for example only
    return a; // undefined, the function has completed, but the setTimeout has not run yet
    a = 1; // it's like doing this after return, has no effect
}