2010-09-17 114 views
6

這是我的Ajax函數的一部分。出於某種原因,我無法弄清楚,我能夠alert() responseText但不能返回 responseText。任何人都可以幫忙嗎?我需要該值用於其他功能。爲什麼我不能從Ajax函數返回responseText?

http.onreadystatechange = function(){ 
    if(http.readyState == 4 && http.status == 200){ 
     return http.responseText; 
    } 
} 
+0

參見[ 如何從函數調用函數返回變量onreadystatechange = function() ](http://stackoverflow.com/questions/1955248/how-to-return-variable-from-the-function-called -by-onreadystatechangefunction)和[AJAX]如何從onreadystatechange = function()函數()返回變量(http://stackoverflow.com/questions/290214/in-ajax-how-to-retrive-variable-from - 內 - 的-的onreadystatechange函數)。 – 2010-09-17 02:23:58

回答

5

您將無法處理從異步回調中返回的返回值。你應該直接處理回調中的responseText,或撥打一個輔助函數來處理響應:

http.onreadystatechange = function() { 
    if (http.readyState == 4 && http.status == 200) { 
     handleResponse(http.responseText); 
    } 
} 

function handleResponse (response) { 
    alert(response); 
} 
+0

你也可以讓'http.onreadystatechange'設置一個回調參數並調用它。看[這個例子](http://stackoverflow.com/questions/290214/in-ajax-how-to-retrive-variable-from-inside-of-onreadystatechange-function/290288#290288)。 – 2010-09-17 02:27:22

+0

@Matthew:是的,這是一個整潔的想法:) – 2010-09-17 02:29:53

0

什麼:

function handleResponse (response) { 
    return response; 
} 

這對於synchrounous和異步模式

+2

以及這與這個問題有什麼關係? – mzzzzb 2012-10-29 07:28:25

0
function getdata(url,callback) 
{ 
    var xmlhttp; 
    if (window.XMLHttpRequest) 
     {// code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
     } 
    else 
     {// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
    xmlhttp.onreadystatechange=function() 
     { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
     { 
     var result = xmlhttp.responseText; 
     callback(result) 
     } 
     } 
    xmlhttp.open("POST",url,true); 
    xmlhttp.send(); 
} 
返回undefined

發送回調函數名稱作爲此函數的第二個參數。 您可以獲得該功能的響應文本。簡單。但是你不能直接從異步調用返回任何東西。

相關問題