首页 > 代码库 > jsonp的封装

jsonp的封装

(function(root){    root["jsonp"]=function(o){        if(typeof(o)!=="object") return;        var    url=o.url,            callback=((typeof(o.callback)==="string")&&o.callback)||"callback",            callbackfn=((typeof(o.callbackfn)==="string")&&o.callbackfn)||("myfn"+parseInt(new Date().getTime()*Math.random())),            callbackdone=((typeof(o.callbackdone)==="function")&&o.callbackdone)||new Function,            data=o.data,            script=document.createElement("script");        url+=dealData(data);        url+=(url.indexOf("?")>-1) ? "&" : "?";        url+=callback+"="+callbackfn+"&_="+new Date().getTime();        script.src=url;        root[callbackfn]=function(){            var arg=arguments;            if(root.navigator.userAgent.toLowerCase().indexOf("msie")>-1){                script.onreadystatechange=function(){                    if(script.readyState=="loaded"||script.readyState=="complete"){                        callbackdone.apply(null,arg);                        script.parentNode.removeChild(script);                    }                }            }else{                script.onload=function(){                    callbackdone.apply(null,arg);                    script.parentNode.removeChild(script);                }            }        }        document.getElementsByTagName("head")[0].appendChild(script);        function dealData(s){            if(s==undefined||s==""||s==null) return "";            if(typeof(s)=="string") return "?"+s;            if(typeof(s)=="object"){                var x,newstr="";                for(var x in s){                    newstr+= x+"="+s[x]+"&";                }                return newstr=="" ? "" : "?"+newstr.substring(0,newstr.lastIndexOf("&"));            }        }    }})(window)

 

jsonp的封装