今天上课学到了jsonp,看了理解,还需要多敲,代码贴出来看看

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="智能社 - zhinengshe.com" />
<meta name="copyright" content="智能社 - zhinengshe.com" />
<title>智能社 - www.zhinengshe.com</title>

<script>

function jsonp(url,data,cbName,fn,timeout,fnFaild){
    
    var fnName = "jsonp_" + Math.random();
    fnName = fnName.replace(".","");
    //data.callback = fnName;
    
    //callback cb  xx  bbb
    data[cbName] = fnName;
    var arr = [];
    for(var name in data){
        arr.push(name + "="+ data[name]);
    }
    
    var str = arr.join("&");
    
    window[fnName] = function (json){
        fn && fn(json);
        oHead.removeChild(oS);
        clearTimeout(timer);
    }

     var oS = document.createElement("script");
     oS.src = url + "?" + str;
     var oHead = document.getElementsByTagName("head")[0];
     oHead.appendChild(oS);
     
     
    if(timeout){
        var timer = setTimeout(function(){
            fnFaild();
            window[fnName] = function(){};    
            oHead.removeChild(oS);
        },timeout);
    }
}
 

window.onload = function(){
    var oText = document.getElementById("txt1");
    //http://sug.so.360.cn/suggest?callback=xxx&word=aa
 var url = "http://sug.so.360.cn/suggest";
 //var url = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su";
    oText.onkeyup = function(){
        jsonp(
            url,
            {word:this.value,wd:this.value},
            "callback",
            //"cb",
            function (json){
            
                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>

 

posted on 2015-08-09 21:43  高尔础础  阅读(140)  评论(0编辑  收藏  举报