码迷,mamicode.com
首页 > Web开发 > 详细

Ajax中自定义发送请求和处理响应对象

时间:2016-05-12 15:48:18      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

Ajax中自定义发送请求和处理响应对象

JavaScript内置一个称为XMLHttpRequest的对象,用于发起Ajax请求并处理Ajax响应。这个对象非常复杂,包含许多支持Ajax的特性和方法。
readyState:请求的状态代码【0(未开始)、1(开启)、2(已传送)、3(接收中)、4(已载入)】
status:HTTP的请求状态代码【404(找不到文件)、200(OK)】
onreadystatechange:请求状态改变时会被调用的函数引用,这个函数事件处理器就是处理响应的地方。
responseText:由服务器返回的响应数据,格式为纯文本字符串。
responseXML:由服务器返回的响应数据,格式为XML节点树构成的对象。
abort():取消请求。
open():准备请求,指定请求的类型、URL和其他细节。
send():传送请求,交给服务器处理。
即使是最基本的Ajax请求,也需要很多javascript代码,因为部分浏览器的不一致。
var request=null;
if(window.XMLHttpRequest){
	try{
		request=new XMLHttpRequest();
	}catch(e){
		request=null;
	}
}else if(window.ActiveXObject){
	try{
		request=new ActiveXObject("Msxm12.XMLHTTP");
	}catch(e){
		try{
			request=new ActiveXObject("Microsoft.XMLHTTP");
		}catch(e){
			request=null;
		}
	}
}
创建XMLHttpRequest对象后,换成设定处理请求的函数,然后开启请求。
request.onreadystatechange=handler;  //服务器响应我们的请求时调用的自定义函数
request.open(type,url,true);    //开启请求,让请求准备发送,同时决定为GET或POST,true决定是异步
GET的话:;request.open("GET","blog.xml",true);
request.send(null);
POST的话:
request.open("POST","addblogentry.php",true);
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
request.send("09/26/2008&These dreams just....&cudeapart.png");

自定义的AjaxRequest对象减轻了制作Ajax请求的痛苦过程:
特性
request:底层的XMLHttpRequest对象存储于这个特性里。
方法
getReadyState();
getStatus();
getResponseText();
getResponseXML();
send();             //AjaxRequest中真正的劳动者,它处理开启和传送请求的细节工作
AjaxRequest.prototype.send=function(type,url,handler,postDataType,postData){
	if(this.request!=null){
		//kill the previous request
		this.request.abort();
		
		try{
			this.request.onreadystatechange=handler;   //自定义的处理器函数
			this.request.open(type,url,true);
			if(type.toLowerCase()=="get"){     //发送get请求
				this.request.send(null);
			}else{                      //发送post请求
				this.request.setRequestHeader("Content-Type",postDataType);
				this.request.send(postData);
			}
		}catch(e){
			alert("Ajax error communicating with the server.\n"+"Details:"+e);
		}
	}
}

var ajaxReq=new AjaxRequest();
ajaxReq.send("GET","movies.xml",handleRequest);



Ajax中自定义发送请求和处理响应对象

标签:

原文地址:http://blog.csdn.net/u012755393/article/details/51367275

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!