面前的说话

  JSONP是JSON with
padding(填充式JSON或参数式JSON)的简写,是以JSON的均等种新办法,常用于服务器和客户端跨源通信,在新生之Web服务被好流行。本文将详细介绍JSONP

 

基础

  JSONP的骨干考虑是,网页通过添加一个<script>元素,向服务器请求JSON数据,这种做法未叫同源政策限制;服务器收到请求后,将数据在一个指定名字的回调函数里传回到

  当通过<script>元素调用数据经常,响应内容必须用javascript函数叫做与圆括号包裹起来。而未是殡葬这样平等段子JSON数据,这就是JSONP中P的意义所在

[1, 2, {"buckle": "my shoe"}]

  JSONP看起和JSON差不多,只不过是吃含有在函数调用中之JSON,它见面发送这样一个打包后底JSON响应:

handleResponse([l, 2, {"buckle": "my shoe"}])

  包裹后底响应会成为<script>元素的内容,它先判断JSON编码后底多少,然后拿其传递让handleResponse()函数

  在实践中,支持JSONP的劳务不见面强制指定客户端必须实现之回调函数名称,比如handleResponse。相反,它们以査询参数的值,允许客户端指定一个函数誉为,然后使用函数名叫失去填响应。许多支撑JSONP的劳务还能够识别出是参数叫做。另一个广泛的参数名称是callback,为了为动用及之劳务支撑类似特殊的需要,就需在代码上做片窜了

  JSONP由少有的构成:回调函数和数目。回调函数是当响应到来时应该在页面中调用的函数。回调函数的讳一般是当恳求中指定的。而数就是是流传回调函数中之JSON数据

http://freegeoip.net/json/?callback=handleResponse

  这个URL是以请一个JSONP地理定位服务。通过査询字符串来指定JSONP服务之回调参数是老大宽泛的,就像面的URL所示,这里指定的回调函数的名字叫handleResponse()

  JSONP是透过动态<script>元素来使的,使用时可以呢src属性指定一个跨域URL。这里的<script>元素以及<img>元素看似,都发生力量不让限制地起另域加载资源。因为JSONP是行之有效之javascript代码,所以在呼吁完成后,即于JSONP响应加载到页面中事后,就会这实施

function handleResponse(response){
    alert ("You're at IP address " + response.ip + ", which is in " + response.city + ", "+ response.region_name);
}
var script = document.createElement("script");
script.src = "http://freegeoip.net/json/?callback=handLeResponse"; document.body.insertBefore(script, document.body.firstChild);

  JSONP之所以在开发人员中颇为流行,主要缘由是其非常简单易用,老式浏览器全部支撑,服务器改造十分小。与图像Ping相比,它的独到之处在能一直看响应文件,支持于浏览器和服务器之间双向通信

  使用<script>元素进行Ajax传输,不让同源策略的影响,因此可采用它由其它的服务器请求数据;而且,包含JSON编码数据的应体会自动解码(即实行)

  不过,JSONP也产生少数沾不足:首先,JSONP是起另域中加载代码执行。如果另外地面不安全,很可能会见在响应中夹带一些恶意代码,而这时除外一心放弃JSONP调用之外,没有办法追究。因此于采取未是自己运维的Web服务经常,一定得保证她安全可靠;其次,要确定JSONP请求是否失败并无易于。虽然HTML5让<script>元素新增了一个onerror事件处理程序,但眼下尚无获取任何浏览器支持。为是,开发人员不得不以计时器检测指定时间外是否接收到了响应。但纵然如此为非可知如愿以偿,毕竟非是每个用户上网的快慢及带富都一模一样

 

简单易行示例

【前端】

<button id="btn">获取信息</button>
<img id="img" height="16" style="display:none" src="data:image/gif;base64,R0lGODlhIAAgALMAAP///7Ozs/v7+9bW1uHh4fLy8rq6uoGBgTQ0NAEBARsbG8TExJeXl/39/VRUVAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFBQAAACwAAAAAIAAgAAAE5xDISSlLrOrNp0pKNRCdFhxVolJLEJQUoSgOpSYT4RowNSsvyW1icA16k8MMMRkCBjskBTFDAZyuAEkqCfxIQ2hgQRFvAQEEIjNxVDW6XNE4YagRjuBCwe60smQUDnd4Rz1ZAQZnFAGDd0hihh12CEE9kjAEVlycXIg7BAsMB6SlnJ87paqbSKiKoqusnbMdmDC2tXQlkUhziYtyWTxIfy6BE8WJt5YEvpJivxNaGmLHT0VnOgGYf0dZXS7APdpB309RnHOG5gDqXGLDaC457D1zZ/V/nmOM82XiHQjYKhKP1oZmADdEAAAh+QQFBQAAACwAAAAAGAAXAAAEchDISasKNeuJFKoHs4mUYlJIkmjIV54Soypsa0wmLSnqoTEtBw52mG0AjhYpBxioEqRNy8V0qFzNw+GGwlJki4lBqx1IBgjMkRIghwjrzcDti2/Gh7D9qN774wQGAYOEfw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DOB9+KhEAIfkEBQUAAAAsAgASAB0ADgAABHgQyEmrBePS4bQdQZBdR5IcHmWEgUFQgWKaKbWwwSIhc4LonsXhBSCsQoOSScGQDJiWwOHQnAxWBIYJNXEoFCiEWDI9jCzESey7GwMM5doEwW4jJoypQQ743u1WcTV0CgFzbhJ5XClfHYd/EwZnHoYVDgiOfHKQNREAIfkEBQUAAAAsAAAPABkAEQAABGeQqUQruDjrW3vaYCZ5X2ie6EkcKaooTAsi7ytnTq046BBsNcTvItz4AotMwKZBIC6H6CVAJaCcT0CUBTgaTg5nTCu9GKiDEMPJg5YBBOpwlnVzLwtqyKnZagZWahoMB2M3GgsHSRsRACH5BAUFAAAALAEACAARABgAAARcMKR0gL34npkUyyCAcAmyhBijkGi2UW02VHFt33iu7yiDIDaD4/erEYGDlu/nuBAOJ9Dvc2EcDgFAYIuaXS3bbOh6MIC5IAP5Eh5fk2exC4tpgwZyiyFgvhEMBBEAIfkEBQUAAAAsAAACAA4AHQAABHMQyAnYoViSlFDGXBJ808Ep5KRwV8qEg+pRCOeoioKMwJK0Ekcu54h9AoghKgXIMZgAApQZcCCu2Ax2O6NUud2pmJcyHA4L0uDM/ljYDCnGfGakJQE5YH0wUBYBAUYfBIFkHwaBgxkDgX5lgXpHAXcpBIsRADs=" alt="loading">
<div id="result"></div>
<script>
var add = (function(){
    var counter = 0;
    return function(){
        return ++counter;
    }
})();
function loadScript(url){
    loadScript.mark = 'load';
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = url;
    script.onload = function(){
        img.style.display = 'none';
        btn.removeAttribute('disabled');
    }
    document.body.appendChild(script);
}
function test(data){
    var sum = add() - 1;
    if(sum < data.length ){
      result.innerHTML += data[sum];    
    }
}
btn.onclick = function(){
    img.style.display = 'inline-block';
    btn.setAttribute('disabled','');
    loadScript('https://www.webhuochai.com/test/getData.php?callback=test');
}
</script>   

【后端】

<?php
function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
$arr = [1,2,3,4,5];
echo test_input($_GET['callback']) ."(" .json_encode($arr) .");";
?>

百度搜索框

  百度搜索框就是应用了JSONP的技巧,在百度搜索的URL中,有用之询问而下 

https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=123&&cb=a

  结果为:

a({q:"123",p:false,s:["12306","12306铁路客户服务中心","12308汽车订票官网","12306火车票网上订票官网","12333","12315","12345","12333社保查询网","123网址之家","12366"]});

  所以,wd为首要词,cb用来JSONP的函数称为。在取之数量中,s为以第一词起之数整合的数

  百度搜索的要紧URL如下

https://www.baidu.com/s?wd=a

  wd为要词,当wd=a时,将开辟关键词为a的网页

<style>
body{margin: 0;}
ul{margin: 0;padding: 0;list-style: none;}
a{color:inherit;text-decoration: none;}
input{padding: 0;border: 0;}
.box{width: 340px;height: 38px;border: 2px solid gray;}
.con{overflow: hidden;}
.input{float: left;width: 300px;height: 38px;}
.search{width: 38px;height: 38px;float: right;background: url('http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/search.png') 0 -38px;}
.list{position: absolute;width: 298px;border: 1px solid #e6e8e9; overflow: hidden;}
.in{line-height: 30px;border-bottom: 1px solid lightblue;cursor:pointer;text-indent: 1em;}
.list .in:last-child{margin-bottom: -1px;}
.in:hover{background-color: #f9f9f9;}
</style>

<div class="box" id="box">
    <div class="con">
        <input class="input" id="search">
        <a target="_blank" id="btn" href="javascript:;" class="search"></a>
    </div>
    <ul class="list" id="list"></ul>        
</div> 
<script>
function loadScript(url){
    loadScript.mark = 'load';
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = url;
    document.body.appendChild(script);
}
function callback(data){
    if(data){
        var arr = data.s;
        var html = '';
        for(var i = 0,len = arr.length; i < len; i++){
            html+= "<li class='in'><a href='https://www.baidu.com/s?wd="+ arr[i]+"' target='_blank' style='display:block'>" + arr[i]+ "</a></li>"
        }
        list.innerHTML = html;        
    }
}
search.onkeyup = function(e){
    e = e || event;
    if(e.keyCode == '13'){
       window.open('https://www.baidu.com/s?wd=' + this.value);
    }
    if(this.value){
        if(search.data != this.value){
            btn.setAttribute('href','https://www.baidu.com/s?wd=' + this.value);
            var that = this;
            loadScript("https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=" + that.value + "&&cb=callback");
        }
    }else{
        list.innerHTML = '';
    }
    search.data = this.value;
}
search.onclick = function(e){
    e = e || event;
    list.style.display = 'block';
    if(e.stopPropagation){
        e.stopPropagation();
    }else{
        e.cancelBubble = true;
    }
}
document.onclick = function(){
     list.style.display = 'none';
}
</script>

最后

  如果以jQuery中行使jsonp技术,需要使用ajax()方法,将datatype设置也’jsonp’,将jsonp设置也函数称,如’callback’

  以上

相关文章

网站地图xml地图