欢迎光临
我们一直在努力

XMLHttpRequest的同步和异步请求-.NET教程,XML应用

建站超值云服务器,限时71元/月

客户端利用xmlhttp发送请求得到服务端应答数据,并用javascript操作dom最终更新页面- 又称无刷新更新页面,有代替传统web开发中采用form(表单)递交方式更新web页面的趋势。

xmlhttp依赖于xmlhttprequest完成从客户端的请求到服务端的应答。xmlhttprequest提供了两个方法open和send。open方法用于初始化xmlhttprequest

对象、指示请求的方式(get、post等)、安全性连接等,在调用open方法后必须调用send方法发送http request(http请求)以返回http reponse(http应答)。

看msdn中对send方法的简介:

this method is synchronous or asynchronous, depending on the value of the basync parameter in the open call. if open is called with basync == false, this call does not return until the entire response is received or the protocol stack times out. if open is called with basync == true, this call returns immediately.

send方法是否同步或异步工作取决于open方法中的basync参数,如果basync == false表示send方法工作在同步状态下,发送http请求后,只有当客户端接收到来自服务端的全部应答数据或协议栈超时返回!反之basync == true,工作在异步状态下,直接返回。

实际运用中,设置basync = true, 使send方法被调用后xmlhttprequest工作在异步状态,如果设为同步状态可能会导致不必要的长时间等待!

另外,无论在同步或异步请求工作状态下,xmlhttprequest如何得到由服务端返回的应答数据?

看下面的示例代码:

<script>

var xmlhttp=null;

function postorder(xmldoc)

{

varxmlhttp = new activexobject("msxml2.xmlhttp");

xmlhttp.open("post", "http://myserver/orders/processorder.asp", false);

xmlhttp.onreadystatechange= handlestatechange;

xmlhttp.send(xmldoc);

}

function handlestatechange()

{

if (xmlhttp.readystate == 4)

{

alert("result = " + xmlhttp.responsexml.xml);

}

}

</script>

服务端返回应答数据并完全被加载, 可通过xmlhttprequest属性readstate获知,其值变为4 – completed (已加载完成),

当readstate变化时会调用xmlhttprequest对象中的回调函数onreadstatechange,在函数中验证xmlhttp.readystate == 4,

这里得到的是xml文档(如果服务端有返回xml文档数据).

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » XMLHttpRequest的同步和异步请求-.NET教程,XML应用
分享到: 更多 (0)

相关推荐

  • 暂无文章