Ajax 操作步骤
1、触发一个客户端事件。
2、创建一个 XMLHttpRequest 对象。
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
3、打开请求
AjaxRequest.open("GET",url,true);
4、发送请求
如果不需要通过 send() 传递数据,则只要传递 null 作为该方法的参数即可。
AjaxRequest.send(null);
5、XMLHttpRequest设置回调函数。
readyState存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
AjaxRequest.onreadystatechange = callback;
function callBack() {
if (AjaxRequest.readyState == 4) {
if (AjaxRequest.status == 200) {
var resp = AjaxRequest.responseText;
} else if (AjaxRequest.status == 404) {
alert("Page not found");
}
} else {
alert("Error: status code is " + AjaxRequest.status);
}
}
Ajax GET
var AjaxRequest;
function AjaxFunction() {
try {
AjaxRequest = new XMLHttpRequest();
} catch (e) {
try {
AjaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
AjaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
//TODO handle the exception
alert("Your browser broke!");
return false;
}
}
}
}
function validateUserId() {
AjaxFunction();
var url = "";
AjaxRequest.open("GET", url, true);
AjaxRequest.send(null);
AjaxRequest.onreadystatechange = callBack();
}
function callBack() {
if (AjaxRequest.readyState == 4) {
if (AjaxRequest.status == 200) {
var resp = AjaxRequest.responseText;
} else if (AjaxRequest.status == 404) {
alert("Page not found");
}
} else {
alert("Error: status code is " + AjaxRequest.status);
}
}
POST
AjaxRequest.open("POST", url, true);
AjaxRequest.send(data);