这篇文章主要介绍了ajax简单异步通信,实例分析了ajax异步通信的技巧与相关注意事项,具有一定参考借鉴价值,需要的朋友可以参考下
本文实例讲述了ajax简单异步通信的方法。分享给大家供大家参考。具体分析如下:
客户端:向服务器发出一个空请求。
代码如下:
<html>
<head>
<title>xmlhttprequest</title>
<script language="javascript">
var xmlhttp;
function createxmlhttprequest(){
if(window.activexobject)
xmlhttp = new activexobject("microsoft.xmlhttp");
else if(window.xmlhttprequest)
xmlhttp = new xmlhttprequest();
}
function startrequest(){
createxmlhttprequest();
xmlhttp.open("get","9-1.aspx",true);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readystate == 4 && xmlhttp.status == 200)
alert("服务器返回: " + xmlhttp.responsetext);
}
xmlhttp.send(null);
}
</script>
</head>
<body>
<input type="button" value="测试异步通讯" onclick="startrequest()">
</body>
</html>
服务器端:向客户端直接返回一个字符串。
<%@ page language="c#" contenttype="text/html" responseencoding="gb2312" %>
<%@ import namespace="system.data" %>
<%
response.write("异步测试成功,很高兴");
%>
问题一:
由于ie 浏览器会自动缓存异步通信的结果,不会实时更新服务器的返回结果。(但firefox 会正常刷新)
为了解决异步连接服务器时ie 的缓存问题,更改客户端代码如下:
var surl = "9-1.aspx?" + new date().gettime(); //地址不断的变化
xmlhttp.open("get",surl,true);
在访问的服务器地址末尾添加一个当前时间的毫秒数参数,使得每次请求的url地址不一样,从而欺骗ie 浏览器来解决ie 缓存导致的更新问题。
问题二:
当测试程序时,如果客户端和服务器端都在同一台计算机上时,异步对象返回当前请求的http状态码 status == 0 ,于是再次更改客户端代码如下:
//if(xmlhttp.readystate == 4 && xmlhttp.status == 200)
if( xmlhttp.readystate == 4)
{
if( xmlhttp.status == 200 || //status==200 表示成功!
xmlhttp.status == 0 ) //本机测试时,status可能为0。
alert("服务器返回: " + xmlhttp.responsetext);
}
于是,最终的客户端代码如下:
<html>
<head>
<title>xmlhttprequest</title>
<script language="javascript">
var xmlhttp;
function createxmlhttprequest(){
if(window.activexobject)
xmlhttp = new activexobject("microsoft.xmlhttp");
else if(window.xmlhttprequest)
xmlhttp = new xmlhttprequest();
}
function startrequest(){
createxmlhttprequest();
var surl = "9-1.aspx?" + new date().gettime(); //地址不断的变化
xmlhttp.open("get",surl,true);
xmlhttp.onreadystatechange = function(){
//if(xmlhttp.readystate == 4 && xmlhttp.status == 200)
if( xmlhttp.readystate == 4)
{
if( xmlhttp.status == 200 || //status==200 表示成功!
xmlhttp.status == 0) //本机测试时,status可能为0。
alert("服务器返回: " + xmlhttp.responsetext);
}
}
xmlhttp.send(null);
}
</script>
</head>
<body>
<input type="button" value="测试异步通讯" onclick="startrequest()">
</body>
</html>
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
ajax机制详解以及跨域通信
ajax无刷新分页的性能优化方法
基于firefox实现ajax图片上传
以上就是ajax简单异步通信实例分析的详细内容。