AjaxJSONP

前方的口舌

  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/Gh7D9qN774wQGAYOE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AqDOB9+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’

  以上

相关文章