XMLHttpRequest 是 AJAX 的基础。XMLHttpRequest 对象用于和服务器交换数据。javascript
建立 XMLHttpRequest 对象的语法:php
variable=new XMLHttpRequest();
如需将请求发送到服务器,咱们使用 XMLHttpRequest 对象的 open() 和 send() 方法:html
open(method,url,async) 规定请求的类型、URL 以及是否异步处理请求。java
send(string) 将请求发送到服务器。web
XMLHttpRequest.setRequestHeader() 是设置HTTP请求头部的方法。此方法必须在 open()
方法和 send()
之间调用。若是屡次对同一个请求头赋值,只会生成一个合并了多个值的请求头。若是没有设置 Accept
属性,则此发送出send()
的值为此属性的默认值*/*
。服务器
语法:myReq.setRequestHeader(header->属性的名称。, value->属性的值。);app
如需得到来自服务器的响应,请使用 XMLHttpRequest 对象的 responseText (得到字符串形式的响应数据)或 responseXML(得到 XML 形式的响应数据。) 属性。异步
3.1 responseText 属性async
若是来自服务器的响应并不是 XML,请使用 responseText 属性。函数
responseText 属性返回字符串形式的响应,所以您能够这样使用:
document.getElementById("myDiv").innerHTML=xmlhttp.responseText
3.2 responseXML属性
若是来自服务器的响应是 XML,并且须要做为 XML 对象进行解析,请使用 responseXML 属性:
请求 books.xml 文件,并解析响应
当请求被发送到服务器时,咱们须要执行一些基于响应的任务。
每当 readyState 改变时,就会触发 onreadystatechange 事件。
readyState 属性存有 XMLHttpRequest 的状态信息。
下面是 XMLHttpRequest 对象的三个重要的属性:
(1)onreadystatechange:存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
(2)readyState:存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。
(3)status:200: "OK",404: 未找到页面
在 onreadystatechange 事件中,咱们规定当服务器响应已作好被处理的准备时所执行的任务。
当 readyState 等于 4 且状态为 200 时,表示响应已就绪:
<html> <head> <script type="text/javascript"> function loadXMLDoc() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","index.php",true); xmlhttp.send(); } </script> </head> <body> <div id="myDiv"><h2>Let AJAX change this text</h2></div> <button type="button" onclick="loadXMLDoc()">Let AJAX change the content!</button> </body> </html>
index.html页面显示为:
index.php内容以下:
<?php echo "AJAX is not a programming language. It is just a technique for creating better and more interactive web applications."; ?>
点击button按钮,部分网页内容动态显示为:
注释:onreadystatechange 事件被触发 5 次(0 - 4),对应着 readyState 的每一个变化。