本文通过三个示例来解释jsonp解决跨域问题
首先理解什么是跨域,简单地说就是因为JavaScript同源策略的限制,ab.com 域名下的js无法操作bc.com或是c.ab.com域名下的对象。
jsonP就是解决跨域问题的方式之一,也是最常用解决方式,json padding json补丁
jsonP并不是一种数据格式,而是将数据放在函数调用的函数参数里
那么些好相应的函数声明,就能将数据传递到前台
示例一:
在html中想要打印php数据
<script type="text/javascript">
var hello = function(data){
console.log(data);
}
</script>
<script src="solve.php?cb=hello"></script>
<?php
$cb = $_GET['cb'];
echo $cb."('hello world')";
//echo "hello('hello world')";
?>
上述分别为html中代码和php代码,控制台输出 hello world
向php传入,cb=hello,cb指的是hello函数名,在php中接收,所以cd只是一个变量名,php中有两种处理数据方式,
一:获取传入的函数名,然后执行函数
二:直接用函数名hello执行(事先商量好的,一般不现实)
示例二:
从网上获取数据:
如借用百度的天气API接口:此处有API链接和返回的JSON返回示例
如点击按钮想要获取对应城市的天气情况
<select id="select">
<option value="101240501">宜春</option>
<option value="101210101">杭州</option>
<option value="101190101">南京</option>
<option value="101010100">背景</option>
</select>
<button id="btn">按钮</button>
<div class="title">
<div class="line"></div>
<div class="titleText">天气预报</div>
<div class="line"></div>
</div>
<div>
<ul id="show">
</ul>
</div>
下面我们要做的就是动态创建一个script标签,让script.src指向链接
如:
btn.onclick = function(){
show.innerHTML = '';
var value = select.value; //获取对应城市的编码
var script = document.createElement('script');
script.src = 'http://cdn.weather.hao.360.cn/api_weather_info.php?app=hao360&_jsonp=smartloaddata&code='+value; //传去对应城市的编码号
document.body.appendChild(script);
}
而需要注意的是链接中_jsonp=后面的是函数名,即_jsonp作用同示例一种cb,传去函数名从而获取到json数据data
函数本身要对数据进行如下操作:
function smartloaddata(data){
console.log(data); //打印数据
var cityName = `${data.area[1][0]}`; //利用数据获取到城市名,如北京
console.log(cityName);
var tag = ''; //定义空字符串
var weather = data.weather; //此处只获取weather中的数据
for(var item of weather){ //遍历weather中的数据
var date = item.date;
var day = item.info.day;
tag += `<li>日期:${date}</li>`;
tag += `<li>白天天气:${day[1]}</li>`;
tag += `<li>白天温度:${day[2]}</li>`;
tag += `<li>白天风向:${day[3]}</li>`;
tag += `<li>白天风速:${day[4]}</li>`;
}
show.innerHTML = cityName + tag; //把获取到的数据添加到div中
}
效果如下:
示例三:
实现动态输入框
效果如下:
此处我们分布实现,
第一步、获取网页数据
在网页中拿到一个连接,如当你输入一个w的时候在network中拿到如下连接:
var textValue = text.value;
$.ajax({
type:'get',
dataType:'jsonp',
url:'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+textValue,
//原连接 https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=w&json=1&p=3&sid=23519_1436_21117_22160&req=2&csor=1&cb=jQuery110205405103515367955_1505657347912&_=1505657347914
jsonp:'cb', //要与连接中函数之前的变量名一致,以便被网页接收
success:function(data){
var str = ''; //存入ul中,方便展示
str += '<ul>';
for(var i = 0; i < data.s.length; i++){
str += '<li>';
str += data.s[i];
str += '</li>';
}
str += '</ul>';
box.innerHTML = str; //把数据添加到div中
}
}
第二步、思考当文字输入,显示提示信息
即添加事件
text.onkeyup = function(){}
第三步、当点击提示信息时,文字显示在输入框中
var lis = $('li');
for(var i of lis){ //遍历li
i.onclick = function(){
text.val($(this).html()); //点击li时,此处文字添加到输入框中
}
}
第四步、整合
此处给提供两种方法
第一种、
var text = document.getElementById('text');
var box = document.getElementById('box');
text.onkeyup = function(){
var textValue = text.value;
$.ajax({
type:'get',
dataType:'jsonp', //类型为jsonp
url:'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+textValue,
// 原链接 https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=w&json=1&p=3&sid=23519_1436_21117_22160&req=2&csor=1&cb=jQuery110205405103515367955_1505657347912&_=1505657347914
jsonp:'cb',
success:function(data){
var str = '';
str += '<ul>';
for(var i = 0; i < data.s.length; i++){
str += '<li>';
str += data.s[i];
str += '</li>';
}
str += '</ul>';
setTimeout(function(){
box.innerHTML = str;
var liArr = document.getElementsByTagName('li');
console.log(liArr);
$('li').each(function(){
this.onclick = function(){
text.value = this.innerHTML;
}
});
},0)
}
})
}
第二种、使用template模板
<script src="template.js"></script>
<script type="text/template" id="template">
<ul>
{{each s as value i}}
<li>{{value}}</li>
{{/each}}
</ul>
</script>
var text = $('#text');
var box = $('#box');
text[0].onkeyup = function(){
var textValue = text.val();
$.ajax({
type:'get',
dataType:'jsonp',
url:'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=' + textValue,
jsonp:'cb',
success:function(data){
var dataText = data.s;
var html = template('template',data);
box.html(html);
setTimeout(function(){ //添加setTimeout使上上面代码都执行完在遍历
var lis = $('li');
for(var i of lis){
i.onclick = function(){
console.log($(this).html());
text.val($(this).html());
}
}
},0)
}
})
}
作者:kuke_kuke
博客链接:http://blog.csdn.net/qq_33599109
欢迎关注支持,谢谢!
图一来源:http://www.cnblogs.com/rainman/archive/2011/02/20/1959325.html