简介
Ajax,是使用XMLHttpRequest对象与服务器进行通信。它可以发送和接收各种格式的信息,包括JSON,XML,HTML和文本文件。它有以下两个功能:
@H_403_4@步骤 1 创建XMLHttpRequest对象
if (window.XMLHttpRequest) { // 新浏览器... httpRequest = new XMLHttpRequest(); } else if (window.ActiveXObject) { // 旧浏览器 httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); }
步骤 2 为XMLHttpRequest对象分配处理函数
方法1 分配函数
httpRequest.onreadystatechange = nameOfTheFunction;
方法2 分配匿名函数
httpRequest.onreadystatechange = function () {};
步骤 3 通过open( ),send( )作出HTTP请求
httpRequest.open('GET','[http://www.example.org/some.file](http://www.example.org/some.file)',true); httpRequest.send();
open( ) 方法
参数1 HTTP请求的方法 GET、 POST、 HEAD 等,需大写
参数2 发送请求的URL
参数3 异步选项
send( ) 方法
如果使用POST方法,则send的参数为想要发送到服务器的任何数据
步骤 4 处理服务器响应
1.检查请求状态
if (httpRequest.readyState === 4) { // Everything is good,the response was received. } else { // Not ready yet. }
请求状态代码
@H_403_4@2.检查HTTP响应代码
if (httpRequest.status === 200) { // Perfect! } else { // There was a problem with the request. // For example,the response may have a 404 (Not Found) // or 500 (Internal Server Error) response code. }
3.进行数据操作
在检查请求的状态和响应的HTTP状态代码之后,可以使用服务器发送的数据进行任何所需的操作。
httpRequest.responseText - 以文本字符串的形式返回服务器响应httpRequest.responseXML- 作为XMLDocument可以使用JavaScript DOM函数遍历的对象返回响应