6

这是我的 Ajax 函数的一部分。由于某种我无法弄清楚的原因,我能够alert() responseText 但无法返回responseText。有人可以帮忙吗?我需要在另一个函数中使用该值。

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

3 回答 3

5

您将无法处理从异步回调返回的返回值。您应该responseText直接在回调中处理,或者调用辅助函数来处理响应:

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

function handleResponse (response) {
    alert(response);
}
于 2010-09-17T02:18:25.437 回答
0

关于什么 :

function handleResponse (response) {
    return response;
}

对于同步和异步模式返回 undefined

于 2012-10-29T00:52:35.007 回答
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();
}

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

于 2014-06-19T11:53:59.447 回答