2010-09-17 91 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

发送回调函数名称作为此函数的第二个参数。 您可以获得该功能的响应文本。简单。但是你不能直接从异步调用返回任何东西。

相关问题