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

如何在AJAX变量分配中添加回调,第1张

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

您正在以异步方式使用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-urlenpred;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-urlenpred;charset=utf-8");    xhr.send(null);    if(xhr.status==200){        return xhr.responseText;    }    else{        return null;    }}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4931739.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-13
下一篇2022-11-12

发表评论

登录后才能评论

评论列表(0条)

    保存