<!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>
jsonp跨域学习以百度为例
最新推荐文章于 2022-03-10 11:20:52 发布