第一步,Ajax操做接口(目的是起一个接口检测做用)ajax
(1)引入接口文件跨域
//定义一个静态方法来实现接口与实现类的直接检验 //静态方法不要写出Interface.prototype ,由于这是写到接口的原型链上的 //咱们要把静态的函数直接写到类层次上 //(1)定义一个接口类 var Interface=function (name,methods) {//name:接口名字 if(arguments.length<2){ alert("必须是两个参数") } this.name=name; this.methods=[];//定义一个空数组装载函数名 for(var i=0;i<methods.length;i++){ if(typeof methods[i]!="string"){ alert("函数名必须是字符串类型"); }else { this.methods.push( methods[i]); } } }; Interface.ensureImplement=function (object) { if(arguments.length<2){ throw new Error("参数必须很多于2个") return false; } for(var i=1;i<arguments.length;i++){ var inter=arguments[i]; //若是是接口就必须是Interface类型 if(inter.constructor!=Interface){ throw new Error("若是是接口类的话,就必须是Interface类型"); } //判断接口中的方法是否所有实现 //遍历函数集合 for(var j=0;j<inter.methods.length;j++){ var method=inter.methods[j];//接口中全部函数 //object[method]传入的函数 //最终是判断传入的函数是否与接口中所用函数匹配 if(!object[method]||typeof object[method]!="function" ){//实现类中必须有方法名字与接口中所用方法名相同 throw new Error("实现类中没有彻底实现接口中的全部方法") } } } }
第二步,实例化一个能够具体的ajax接口数组
var AjaxHandler=new Interface("AjaxHandler",["request","createXhrObject"]);
第三步,针对接口的ajax实现类浏览器
(1)定义一个空类函数
var SimpleHandler=function(){};
(2)在该空类上直接扩展原型---实现接口里面的方法post
SimpleHandler.prototype={ /* * method:get post * url:请求地址 * callback:回调函数 * postVars:传入参数 * */ request:function (method,url,callback,postVars) { //1,使用工厂获得xhr对象 var xhr=this.createXhrObject(); xhr.onreadystatechange=function () { //4表明的意思是交互完成 if(xhr.readyState!=4) return; //200值的是正常交互完成 //404文件未找到 //500 内部程序出错 (xhr.status==200)?callback.success(xhr.responseText,xhr.responseXML): callback.failure(xhr.status); } //打开连接 xhr.open(method,url,true); //设置参数 if(method!="POST"){ postVars=null; } xhr.send(postVars); }, //2,获取xhr的方法--不一样浏览器不同 createXhrObject:function () { var methods=[ function () {return new XMLHttpRequest();}, function () {return new ActiveXObject("Microsoft.XMLHTTP");} ]; //利用try--catch 制做一个智能循环体 for(var i=0;i<methods.length;i++){ try{ methods[i](); }catch(e) { continue;//回到循环开始的地方从新开始 } this.createXhrObject=methods[i]();//很是重要,只有这样才能确保不用每一次请求,全循环数组 return methods[i](); } //若是全不对则报错 throw new Error("error"); } };
第三步,使用检验this
(1)实例化对象url
var myHandler=new SimpleHandler();
(2)接口检验实现类是否彻底实现接口中的方法spa
Interface.ensureImplement(myHandler,AjaxHandler);//检验是否实现接口中全部方法
(3)定义一个回调对象prototype
var callback={ success:function (responseText) { alert("ok"); }, failure:function (status) { alert(status+"failure") } };
(4)最终的使用格式
myHandler.request("POST","http://www.baidu.com",callback);//若url为""会默认为本地的连接,其余正确的连接,会出现跨域问题