AJAX的使用

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

大概流程就是这样子,介绍完毕。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容