2.2.3 Ajax编程步骤
Ajax编程千篇一律分为以下几步:
1. 创建XMLHttpRequest对象。
......
function getXMLHttpRequest() {
var xhr = null;
// 针对FireFox,Mozillar,Opera,Safari,IE7,IE8
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else { // 针对IE6,IE5.5,IE5
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
......
2. 注册回调函数。
......
xhr.onreadystatechange = function() {
// 判断对象的交互状态是否交互完成
if ( xhr.readyState == 4 ) {
...
// 判断浏览器与服务器的Http交互是否成功
if ( xhr.status == 200 ) {
...
// 接受服务器端反馈的数据
var txt = xhr.responseText;
...
} else {
...
}
} else {
...
}
......
3. 设置连接信息。
......
// get 同步方式
xhr.open("get", url, false);
// get 异步方式
xhr.open("get", url, true);
// post 同步方式
xhr.open("post", url, false);
// post 异步方式
xhr.open("post", url, false);
// 默认情况下为异步方式
xhr.open("get", url);
xhr.open("post", url);
......
4. 发送数据。
......
// 用get方式连接信息时,请求参数param写在了url后面.
// 如:var url = "../../findbyfalse.list_grad?page=" + param
xhr.send(null);
// 用post方式连接信息时
xhr.send(param);
......
5. 接收相应数据。与步骤2注册回调函数合并参见步骤2
6. 写服务器端的响应
......
// 服务器端设置响应内容形式为纯文本形式
response.setContentType("text/plain;charset=utf-8");
// 服务器端创建输出流
PrintWriter out = response.getWriter();
// 向浏览器端发送数据
out.print(data);
out.flush();
out.close();