AJAX = Asynchronous JavaScript and XML
用途
其实就是希望动态更新网页内容。
Update a web page without reloading the pageRequest data from a server.
after the page has loaded Receive data from a server
or after the page has loadedSend data to a server.in the background
工作过程描述
工作过程代码该如何写
首先创建XMLHttpRequest对象
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
看下XMLHttpRequest有哪些常用的方法
Method | Description |
---|---|
setRequestHeader(header, value) | Adds HTTP headers to the request <br /> header: specifies the header name value: specifies the header value |
open(method, url, async) | Specifies the type of request <br /> method: the type of request: GET or POST url: the server (file) location async: true (asynchronous) or false (synchronous) |
send() | Sends the request to the server (used for GET) |
send(string) | Sends the request to the server (used for POST) |
onreadystatechange | Stores a function (or the name of a function) to be called automatically each time the readyState property changes |
然后是配置请求信息
xhttp.open("GET", "ajax_info.txt", true);
接着是发送请求
// if need
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
// or
xhttp.send("fname=Henry&lname=Ford");
监听响应事件,做相应的处理
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// 这就是传说中的动态更新网页内容
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
XMLHttpRequest的事件属性描述
Property | Description |
---|---|
readyState | Holds the status of the XMLHttpRequest. Changes from 0 to 4: 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready |
status | 200: "OK" 404: Page not found |
大概流程就是这样子,介绍完毕。
网友评论