jsonp跨域学习以百度为例

来源:互联网 发布:重装系统数据备份 编辑:程序博客网 时间:2024/05/22 04:36
<!doctype html><html><head><meta charset="utf-8"><meta name="author"/><meta name="copyright"/><title></title><script>function jsonp(url,data,fn,timeout,fnFaild){      var fnName = ("jsonp_"+Math.random()).replace(".","");      //alert(fnName);      window[fnName] = function (json){      fn && fn(json);             //清除标签      document.body.removeChild(oS);            //清除定时器      clearTimeout(timer);            //资源回收      window[fnName] = null;         };      var arr = [];   data.cb = fnName;   for(var i in data){      arr.push(i + "=" + data[i]);   }   var str = arr.join("&");      var oS = document.createElement("script");   oS.src = url + "?" + str;   document.body.appendChild(oS);      if(timeout){      var timer = setTimeout(function(){         fnFaild && fnFaild();                    window[fnName] = function(){};      },timeout);   }}window.onload = function(){    var oText = document.getElementById("txt1");   var oUl   = document.getElementById("ul1");      var url = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su";            oText.onkeyup = function(){       jsonp(         url,         {            wd:oText.value          },         function(json){            //alert(json.s);            var oUl = document.getElementById("ul1");                        oUl.innerHTML = "";            for(var i = 0; i < json.s.length; i++){               var oLi = document.createElement("li");               oLi.innerHTML = json.s[i];               oUl.appendChild(oLi);            }         },         1000,         function(){            alert("失败");            }                  );    };};</script> </head><body><input id="txt1" type="text" value="" /><ul id="ul1"></ul></body></html>
0 0
原创粉丝点击