文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>跨域的异步请求四

跨域的异步请求四

时间:2011-02-13  来源:司徒正美

//2011.2.13 by 司徒正美
      ;;;(function(WIN,DOM,undefined){
        var _dom = WIN.dom,
        slice = Array.prototype.slice,
        dom = {
          mix : function(target, source ,override) {
            var i, ride = (override === void 0) || override;
            for (i in source) {
              if (ride || !(i in target)) {
                target[i] = source[i];
              }
            }
            return target;
          },
          noConflict: function(  ) {//防止命名冲突,请先行引用其他库再引用本框架
            WIN.dom = _dom;//这是别人的
            return dom;//请赋以其一个命名空间
          },
          jsonp:function(){
            var self = arguments.callee,
            args = self.args(arguments),
            url = args[0],
            data = args[1],
            callback = args[2],
            errback  = args[3],
            jsonpkey = args[4],
            jsonpname = "callback"+1*new Date,
            jsonpval = "dom.jsonp."+jsonpname,
            add  = /\?/.test( url ) ? "&" : "?",
            script =  DOM.createElement("script"),
            query =[];
            data[jsonpkey]  = jsonpval
            self[jsonpname] = function(json){
              script.jsonp = 1;
              callback(json);
            }
            for(var i in data){
              query.push(i +"="+data[i])
            }
            url = url + add + query.join("&")
            script.src = url;
            script.onload = script.onreadystatechange = function(){
              if( -[1,] || /loaded|complete/i.test(this.readyState)){
                self.removeScript(this,errback,jsonpname);
              }
            }
            script.onerror = function(){
              self.removeScript(this,errback,jsonpname);
            }
            var head = DOM.getElementsByTagName("head")[0];
            head.appendChild(script);
          }
        }
        dom.mix(dom.jsonp, {
          args : function(obj){
            var array = slice.call(obj)
            if(array.length === 1){
              obj = array[0]
              array = [obj.url,obj.data,obj.callback,obj.errback,obj.jsonpkey]
            }
            if(typeof array[1] === "function"){
              array.splice(1,0,{});//让正向回调回到其正确位置
            }
            if(typeof array[3] !== "function"){
              array.splice(3,0,function(){});//让负向回调回到其正确位置
            }
            array[4] =  array[4] || "jsoncallback";
            return array;
          },
          removeScript: function(script,error,jsonpname){
            if(typeof script.jsonp === "undefined" ){
              error();
            }
            if (script.clearAttributes) {
              script.clearAttributes();
            } else {
              script.onload = script.onreadystatechange = script.onerror = null;
            }
            script.parentNode.removeChild(script);
            delete this[jsonpname];
          }
        });

        window.dom = dom;
      })(this,this.document);

dom.jsonp.args会对dom.jsonp的参数进行了重写,因此dom.jsonp支持多种传参方式:

        dom.jsonp(url,args,callback,errback,jsonpkey)
        dom.jsonp(url,callback,errback,jsonpkey)
        dom.jsonp(url,callback,jsonpkey)
        dom.jsonp(url,callback)
        dom.jsonp({
          url:'',
          callback:function(){}
          //其他.....
        })

使用示例:

 dom.jsonp("http://del.icio.us/feeds/json/fans/stomita",function(json){alert(json)},"callback");

下面例子请用firebug查看请求状态与结果!

<!doctype html> <html> <head> <title>jsonp by 司徒正美</title> <script> var log = function (s) { window.console && window.console.log(s); } ;;;(function(WIN,DOM,undefined){ var _dom = WIN.dom, slice = Array.prototype.slice, dom = { mix : function(target, source ,override) { var i, ride = (override === void 0) || override; for (i in source) { if (ride || !(i in target)) { target[i] = source[i]; } } return target; }, noConflict: function( ) {//防止命名冲突,请先行引用其他库再引用本框架 WIN.dom = _dom;//这是别人的 return dom;//请赋以其一个命名空间 }, jsonp:function(){ var self = arguments.callee, args = self.args(arguments), url = args[0], data = args[1], callback = args[2], errback = args[3], jsonpkey = args[4], jsonpname = "callback"+1*new Date, jsonpval = "dom.jsonp."+jsonpname, add = /\?/.test( url ) ? "&" : "?", script = DOM.createElement("script"), query =[]; data[jsonpkey] = jsonpval self[jsonpname] = function(json){ script.jsonp = 1; callback(json); } for(var i in data){ query.push(i +"="+data[i]) } url = url + add + query.join("&") script.src = url; script.onload = script.onreadystatechange = function(){ if( -[1,] || /loaded|complete/i.test(this.readyState)){ self.removeScript(this,errback,jsonpname); } } script.onerror = function(){ self.removeScript(this,errback,jsonpname); } var head = DOM.getElementsByTagName("head")[0]; head.appendChild(script); } } dom.mix(dom.jsonp, { args : function(obj){ var array = slice.call(obj) if(array.length === 1){ obj = array[0] array = [obj.url,obj.data,obj.callback,obj.errback,obj.jsonpkey] } if(typeof array[1] === "function"){ array.splice(1,0,{});//让正向回调回到其正确位置 } if(typeof array[3] !== "function"){ array.splice(3,0,function(){});//让负向回调回到其正确位置 } array[4] = array[4] || "jsoncallback"; return array; }, removeScript: function(script,error,jsonpname){ if(typeof script.jsonp === "undefined" ){ error(); } if (script.clearAttributes) { script.clearAttributes(); } else { script.onload = script.onreadystatechange = script.onerror = null; } script.parentNode.removeChild(script); delete this[jsonpname] } }); window.dom = dom; })(this,this.document); window.onload = function(){ dom.jsonp("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json",function(json){log(json)},function(){ log("出错了") },"jsoncallback"); dom.jsonp("http://del.icio.us/feeds/json/fans/stomita",function(json){log(json)},function(){ log("出错了") },"callback"); dom.jsonp("88888888888888888",{ partTag: 'mtvo', iod: 'hlPrice', viewType: 'json', results: '100', query: 'ipod'},function(json){log(json)},function(){ log("出错了") },"callback"); dom.jsonp("http://api.cnet.com/restApi/v1.0/techProductSearch",{ partTag: 'mtvo', iod: 'hlPrice', viewType: 'json', results: '100', query: 'ipod'},function(json){log(json)},function(){ log("出错了") },"callback"); } </script> </head> <body> </body> </html>

运行代码

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载