AJAX 学习笔记[一] 简单的异步通信示例
客户端:向服务器发出一个空请求。
9-1.html 代码如下:
| <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> |
服务器端:向客户端直接返回一个字符串。
9-1.aspx 代码如下:
| <%@ 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> |
| 作者: XuGang 网名:钢钢 |
| 出处: http://xugang.cnblogs.com |
| 声明: 本文版权归作者和博客园共有。转载时必须保留此段声明,且在文章页面明显位置给出原文连接地址! |
浙公网安备 33010602011771号