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

来源:互联网 发布:网络固定电话软件 编辑:程序博客网 时间:2024/06/11 21:22
         AJAX 是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
        在js中使用ajax请求一般包含三个步骤:
              1、创建XMLHttp对象
              2、发送请求:包括打开链接、发送请求
              3、处理响应
        在不使用任何的js框架的情况下,要想使用ajax,可能需要向下面一样进行代码的编写

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());

如果在比较复杂的业务逻辑里面使用这种ajax请求,会使得代码很臃肿,不方便重用,并且可以看到,可能在服务器响应成功后要处理一个业务逻辑操作,这个时候不得不把操作写在onreadystatechage方法里面。
为了方便代码的重用我们可以做出如下处理;      1、服务器响应成功后,要处理的业务逻辑交给开发人员自己处理      2、对请求进行面向对象的封装处理之后看起来应该像下面这个样子:
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操作,读者有不懂的地方可以慢慢思考或者在此留言 



















2 0
原创粉丝点击