function initRequest()
{
var request = false;
if(window.XMLHttpRequest) { //FireFox
request = new XMLHttpRequest();
if (request.overrideMimeType) {
request.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject) { //IE
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!request) {
window.alert("Create request error!");
return false;
}
return request;
}
var http_request;
function send(sendUrl,sendData)
{
http_request = initRequest();
sendUrl += "&random="+Math.random(); //在URL后添加这个,可以保证不被缓存
http_request.onreadystatechange = ajax_call_back;//指定请求返回时的回调函数
//get
http_request.open("GET", sendUrl,true);
http_request.send(sendData);
//post
//http_request.open("POST", sendUrl, true);
//http_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//http_request.send(sendData);
}
function ajax_call_back()
{
//readyState共有5中状态,0未初始化,1已初始化,2发送请求,3开始接收结果,4接收结果完毕。
//status服务器响应状态码
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var str = http_request.responseText;
alert("返回数据为:"+str);
}
else if(http_request.status == 404){
alert("请求资源不存在!");
}
else {
alert("Ajax请求失败,错误状态为:"+http_request.status);
}
}
}
XMLHttpRequest 对象 |
|
属性 |
|
readyState | 请求状态,开始请求时值为0直到请求完成这个值增长到4 |
responseText | 目前为止接收到的响应体,readyState<3此属性为空字符串,=3为当前响应体,=4则为完整响应体 |
responseXML | 服务器端相应,解析为xml并作为Document对象返回 |
status | 服务器端返回的状态码,=200成功,=404表示“Not Found” |
statusText | 用名称表示的服务器端返回状态,对于“OK”为200,“Not Found”为400 |
方法 |
|
setRequestHeader() | 向一个打开但是未发生的请求设置头信息 |
open() | 初始化请求参数但是不发送 |
send() | 发送Http请求 |
abort() | 取消当前相应 |
getAllResponseHeaders() | 把http相应头作为未解析的字符串返回 |
getResponseHeader() | 返回http相应头的值 |
事件句柄 |
|
onreadystatechange | 每次readyState改变时调用该事件句柄,但是当readyState=3有可能调用多次 |