JSONP 跨域的原理

185 阅读1分钟




搜所





    JSON相比大家都已经很了解了,那么JSONP又是个什么鬼,JSONP是利用在页面中动态创建script节点的方法向不同域提交HTTP请求的方法称为JSONP,通俗的来说,就是在服务端输出JSON数据并执行回调函数。

    var _script= document.createElement(“script”);
    _script.type = “text/javascript”;
    _script.src = “xxxxx”;
    document.getElementsByTagName(“head”)[0].appendChild(_script);

    (function (){

        var _btn = document.getElementById("search");
        var _jsonp_con = document.getElementById("jsonp_con");
        var _in = document.getElementById("in");
    
        _in.onkeyup = function (){
            if(this.value != ""){
                var _script = document.createElement("script");
                _script.src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd="+ this.value +"&cb=Baidu";
                document.body.appendChild(_script);
                _script.onload = _script.onreadystatechange = function (){
                    if(_script.readyState=="loaded" || _script.readyState=="complete" || !_script.readyState){
                        document.body.removeChild(_script);
                    }
                }
            }
        };
    
        _in.onblur = function (){
            setTimeout(function (){
                _jsonp_con.style.display = "none";
            },200)
        };
    
        _btn.onclick = function (){
            window.location='http://www.baidu.com/s?wd='+_in.value;
        }

    })();

    function Baidu(data){

        var _jsonp_con = document.getElementById("jsonp_con");
        var _ul = _jsonp_con.children[0];
        var _arr = data.s;
        var _html = '';
    
        if(_arr.length>0){
            _jsonp_con.style.display = "block";
            for(var i=0;i<_arr.length; i++){
                _html += "<li><a target='_blank' href='http://www.baidu.com/s?wd="+data.q+"'>"+ _arr[i] +"</a></li>"
            }
            _ul.innerHTML = _html;
        }else{
            _jsonp_con.style.display = "none";
        }

    }