AJAX的两个主要功能使您可以执行以下操作:
- 向服务器发出请求,而无需重新加载页面
- 从服务器接收和处理数据
一、发出HTTP请求:
例子:
<button id="ajaxButton" type="button">Make a request</button>
<script>
(function() { var httpRequest;document.getElementById("ajaxButton").addEventListener('click', makeRequest);
//单击按钮,调用makeRequest()
函数
function makeRequest() {
//1、向服务器发出请求
httpRequest = new XMLHttpRequest();
//
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
//2、请求后,收到回复前,设置onreadystatechange
对象的属性,来告诉XMLHttp请求对象哪个JavaScript函数将处理响应,
httpRequest.onreadystatechange = alertContents;
//3、收到响应后,再调用HTTP请求对象的open()
和send()
方法来实际发出请求,// open('请求类型','URL',可选|请求是否异步(默认true))
httpRequest.open('GET', 'test.html');
//send()
方法的参数可以是POST
-ing请求时要发送到服务器的任何数据,如果要进行post数据处理,
//httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(); }
//处理响应函数
function alertContents() {
//4、检查请求状态,如状态的值为xml...DONE,表已收到完整的服务器响应
if (httpRequest.readyState === XMLHttpRequest.DONE) {
//5、检查HTTP响应状态码
if (httpRequest.status === 200) {
///6、对服务器发送的数据进行操作,需要两个方法:
// httpRequest.responseText
–以文本字符串形式返回服务器响应
// httpRequest.responseXML
–将响应作为XMLDocument
可以使用JavaScript DOM函数遍历的对象返回
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
})();
</script>
2)如果发送通信错误:
则onreadystatechange
在访问响应状态时,方法中将引发异常 (请求后,回复前,在此阶段设置onreadystatechange
对象的属性并在请求更改状态时调用该函数后命名)
function alertContents() { // try { // if (httpRequest.readyState === XMLHttpRequest.DONE) { if (httpRequest.status === 200) { alert(httpRequest.responseText); } else { alert('There was a problem with the request.'); } } } // catch( e ) { // alert('Caught Exception: ' + e.description); } }