Why can I not return responseText from an Ajax function? [duplicate]

断了今生、忘了曾经 提交于 2019-11-28 01:13:22

You will not be able to handle the return value that you are returning from your asynchronous callback. You should handle the responseText within the callback directly, or call a helper function to handle the response:

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

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

What about :

function handleResponse (response) {
    return response;
}

which return undefined for synchrounous and asynchronous modes

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();
}

send a call back function name as second arguement to this function. You can get the response text for that function. simple. But you can't directly return anything from an asynchronous call.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!