2013-10-06 101 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