2013-10-06 53 views
2

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

我很感激任何帮助。

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; 
} 
+0

ur在你实际收到响应之前返回响应 –

回答

3

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,这也是异步的。以下代码在结束之前不会挂起1亿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 
} 
+0

谢谢你们的帮助!澳航的解决方案似乎完美。 – Albert