Javascript 将XMLHttpRequest.responseText存储到变量中

Javascript 将XMLHttpRequest.responseText存储到变量中,javascript,ajax,google-chrome-extension,Javascript,Ajax,Google Chrome Extension,不太熟悉XMLHttpRequests,但我正在使用谷歌浏览器扩展中的跨源函数。这非常有效(我可以确认我获得了所需的适当数据),但我似乎无法将其存储在“response”变量中 我非常感谢你的帮助 function getSource() { var response; var xmlhttp; xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if (xmlh

不太熟悉
XMLHttpRequest
s,但我正在使用谷歌浏览器扩展中的跨源函数。这非常有效(我可以确认我获得了所需的适当数据),但我似乎无法将其存储在“response”变量中

我非常感谢你的帮助

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
,这也是异步的。下面的代码在结束之前不会挂起100000秒,而是立即结束,然后等待计时器启动以运行该函数。但是到那时,这个任务就没用了,因为它不是全局的,其他任何东西都不在任务的范围之内

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
}

在你收到回复之前,你会回复我谢谢你们的帮助!澳航的解决方案似乎运作完美。