小编典典

如何在AJAX变量分配中添加回调

ajax

我有一个responce通过AJAX函数分配的变量send()。当我做作业时…

responce = send();

在发送之前响应返回给了我undefined一个回音,如何添加回调以防止这种情况发生?

编辑:我要问的澄清。

它仍然返回未定义。我用send send函数在onreadystatechange函数上为变量分配变量,但是当我的代码正在执行时..
send()可以返回之前,response返回未定义状态。如何停止响应下的代码继续运行,直到分配了响应后才发送值?

编辑2:

以下代码是我的发送函数…

 function send(uri)
{
    var xhr = new XMLHttpRequest();
    xhr.open("POST",uri,true);
    xhr.onreadystatechange = function (send){
        if(xhr.readyState == 4){
            return xhr.responseText;
        }   
    }
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    xhr.send(null);
}

阅读 216

收藏
2020-07-26

共1个答案

小编典典

您正在以异步方式使用Ajax,但是您将其视为同步。

在执行最初的send调用后的其余代码时,异步调用将停止工作。由于代码未返回任何内容,因此您未定义。

如果查看XMLHttpRequest对象,则open方法中的第三个参数是异步标志。

open("method", "URL"[, asyncFlag[, "userName"[, "password"]]])

将其设置为true [默认关闭]将进行异步调用。将其设置为false将使其同步。

使用同步调用的问题是它将锁定用户的浏览器,直到返回调用为止。这意味着动画gif内容,浏览器计时器停止等等。如果服务器需要永远的响应,则用户将无能为力。

最好的解决方案是避免使用同步调用。使用回叫继续执行代码。

因此,根据您的修改,我将使用基本解决方案来修改我的回复

function send(uri, callback)
{
    var xhr = new XMLHttpRequest();
    xhr.open("POST",uri,true);
    xhr.onreadystatechange = function (send){
        if(xhr.readyState == 4){  //You really should check for status here because you can get 400, 500, etc
            callback(xhr.responseText);
            //return 
        }   
    }
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    xhr.send(null);
}



function myFunction(){

  var myUrl = "foo.php";

  //show a loading message or soemthing
  var someDiv = document.getElementById("loadingMessage");
  someDiv.style.display = "block";

  //Second half of your function that handles what you returned.
  function gotData( value ){
      someDiv.style.display = "none";
      alert(value);
  }

  send(myUrl, gotData);

}

如果您确实想进行同步并且不介意锁定用户的浏览器

function send(uri, callback)
{
    var xhr = new XMLHttpRequest();
    xhr.open("POST",uri,false);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    xhr.send(null);
    if(xhr.status==200){
        return xhr.responseText;
    }
    else{
        return null;
    }
}
2020-07-26