JS原生JSONP的使用

时间:2022-12-18 09:28:57

JSONP是JSON with padding(填充式JSON或参数式JSON)的简写,是应用JSON的一种新方法,常用于服务器与客户端跨源通信,在后来的Web服务中非常流行。

基础
  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相比,它的优点在于能够直接访问响应文本,支持在浏览器与服务器之间双向通信  使用
<button id="btn">获取信息</button>
<img id="img" height="16" style="display:none" src="/load.jpg" 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()方法,下篇文章见