A5下载文章资讯

分类分类

js实现对ajax请求面向对象的封装

2016-01-09 09:29作者:fang

AJAX 是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

在js中使用ajax请求一般包含三个步骤:

1、创建XMLHttp对象

2、发送请求:包括打开链接、发送请求

3、处理响应

在不使用任何的js框架的情况下,要想使用ajax,可能需要向下面一样进行代码的编写

<span style="font-size:14px;">var xmlHttp = xmlHttpCreate();//创建对象

xmlHttp.onreadystatechange = function(){//响应处理

if(xmlHttp.readyState == 4){

console.info("response finish");

if(xmlHttp.status == 200){

console.info("reponse success");

console.info(xmlHttp.responseText);

}

}

}

xmlHttp.open("get","TestServlet",true);//打开链接

xmlHttp.send(null);//发送请求

function xmlHttpCreate() {

var xmlHttp;

try {

xmlHttp = new XMLHttpRequest;// ff opera

} catch (e) {

try {

xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// ie

} catch (e) {

try {

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e) {

}

}

}

return xmlHttp;

}

console.info(xmlHttpCreate());</span>

如果在比较复杂的业务逻辑里面使用这种ajax请求,会使得代码很臃肿,不方便重用,并且可以看到,可能在服务器响应成功后要处理一个业务逻辑操作,这个时候不得不把操作写在onreadystatechage方法里面。

为了方便代码的重用我们可以做出如下处理;

1、服务器响应成功后,要处理的业务逻辑交给开发人员自己处理

2、对请求进行面向对象的封装

处理之后看起来应该像下面这个样子:

<pre code_snippet_id="342814" snippet_file_name="blog_20140513_2_2489549" name="code" class="javascript">window.onload = function() {

document.getElementById("hit").onclick = function() {

console.info("开始请求");

ajax.post({

data : 'a=n',

url : 'TestServlet',

success : function(reponseText) {

console.info("success : "+reponseText);

},

error : function(reponseText) {

console.info("error : "+reponseText);

}

});

}

}

var ajax = {

xmlHttp : '',

url:'',

data:'',

xmlHttpCreate : function() {

var xmlHttp;

try {

xmlHttp = new XMLHttpRequest;// ff opera

} catch (e) {

try {

xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// ie

} catch (e) {

try {

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e) {

}

}

}

return xmlHttp;

},

post:function(jsonObj){

ajax.data = jsonObj.data;

ajax.url = jsonObj.url;

//创建XMLHttp对象,打开链接、请求、响应

ajax.xmlHttp = ajax.xmlHttpCreate();

ajax.xmlHttp.open("post",ajax.url,true);

ajax.xmlHttp.onreadystatechange = function(){

if(ajax.xmlHttp.readyState == 4){

if(ajax.xmlHttp.status == 200){

jsonObj.success(ajax.xmlHttp.responseText);

}else{

jsonObj.error(ajax.xmlHttp.responseText);

}

}

}

ajax.xmlHttp.send(ajax.data);

}

};

上述代码实现了类似jquery中的ajax操作,希望对大家的学习有所帮助。

展开全部

相关

说两句网友评论
    我要跟贴
    取消