栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在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;    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/380419.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号