介绍:
AJAX 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下
AJAX = 异步 JavaScript 和 XML。
AJAX 是一种用于创建快速动态网页的技术。
通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。
有很多使用 AJAX 的应用程序案例:新浪微博、Google 地图、开心网等等。
</pre><pre name="code" class="html"><html><head><script type="text/javascript">function loadXMLDoc(){.... AJAX script goes here ...}</script></head><body><div id="myDiv"><h3>Let AJAX change this text</h3></div><button type="button" onclick="loadXMLDoc()">Change Content</button></body></html>
XMLHttpRequest 是 AJAX 的基础。
XMLHttpRequest 对象所有现代浏览器均支持 XMLHttpRequest 对象(IE5 和 IE6 使用 ActiveXObject)。
XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
创建 XMLHttpRequest 对象的语法:variable=new XMLHttpRequest();
XMLHttpRequest 对象用于和服务器交换数据。
如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:
xmlhttp.open("GET","test1.txt",true);xmlhttp.send();方法描述
open(method,url,async)
规定请求的类型、URL 以及是否异步处理请求。
send(string)将请求发送到服务器。
Async = true当使用 async=true 时,请规定在响应处于 onreadystatechange 事件中的就绪状态时执行的函数:
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }xmlhttp.open("GET","test1.txt",true);xmlhttp.send();Async = false如需使用 async=false,请将 open() 方法中的第三个参数改为 false:
xmlhttp.open("GET","test1.txt",false);我们不推荐使用 async=false,但是对于一些小型的请求,也是可以的。
请记住,JavaScript 会等到服务器响应就绪才继续执行。如果服务器繁忙或缓慢,应用程序会挂起或停止。
注释:当您使用 async=false 时,请不要编写 onreadystatechange 函数 - 把代码放到 send() 语句后面即可:
xmlhttp.open("GET","test1.txt",false);xmlhttp.send();document.getElementById("myDiv").innerHTML=xmlhttp.responseText;