一、跨域访问的思路
jsonp与ajax虽是两个不同的概念,但jquery的$.ajax实现了jsonp的跨域访问。此方法的跨域访问数据需依赖要被访问的服务端脚步能根据jsonp:'jsoncallback'生成包含json数据的jsoncallback(json);的代码,如果服务端返回的直接是json数据,前端脚本就不能处理数据。
既然js不能跨域访问数据,那可不可以通过后端访问目标服务器,由后端对目标服务器返回的json数据返回给前端,达到跨域访问数据的目的呢(很显然这需牺牲前端获取数据的反应时间)。
二、本地测试跨域访问json数据
本文以php语言编写后台服务脚本,后台服务脚本的主要作用是异步接受前端发送的数据,再将数据发送到目标服务器,将目标服务器返回的数据返回到前端。(本测试模拟目前服务器返回json数据,而非jsonp)
前端页面代码:inde.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jsonp</title>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// var songid = 1087965;
// var pdata = {'cat':'referrer','rid':'undefined','id':songid,'end':17,'start':0,'callback':'jscall'};
$(function(){
var que = $('input[name=wq]');
var wq = que.val();
check(wq);
que.blur(function(){
wq = que.val();
check(wq);
});
$('#btn').click(function(){
$.ajax({
url:"s.php",
type:"GET",
dataType:'json',
data:{"wq":wq},
success:function(data){
$.each(data.s,function(i,item){
console.log(item);//对目标服务器返回的json数据进行操作
})
}
});
});
});
var check = function(wq){
if(wq=="")
{
$('#btn').attr("disabled","disabled");
}else
{
$('#btn').removeAttr("disabled");
}
};
</script>
</head>
<body>
<input type="text" name="wq" id="query"/>
<button id='btn'>点击我</button>
</body>
</html>
后台脚本 s.php
<?php
require dirname(dirname(dirname(__FILE__))).'/core/requests.php';//实现php curl类库
require dirname(dirname(dirname(__FILE__))).'/core/util.php';
if(isset($_GET['wq']))
{
$wd = $_GET['wq'];
}else
{
$wd = '跨域中介测试';
}
$data = array(
'wd' => $wd,
'json' =>1,
'p' => 3,
'cb' =>'jcall',
'_' =>time()
);
$url = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su';
$html = requests::get($url,$data);
$headers = requests::$info;
if(isset($headers['content_type']))
{
$chpattern = '/charset\=(.+)[\;]?/is';
preg_match_all($chpattern, $headers['content_type'], $chmatches);
if(!empty($chmatches[1]))
{
$charset = strtoupper(trim($chmatches[1][0]));
}
}
if(isset($charset))
{
if(preg_match('/GB/is', $charset))
{
$html = iconv($charset, 'UTF-8', $html);
}
}
$pattern = '/[a-zA-Z\.\_]+\((\{.+\})\)\;$/is';
preg_match_all($pattern, $html, $matches);
if(!empty($matches[1]))
{
echo $matches[1][0];//返回目标服务器返回的json数据
}else
{
$ret = array(
'status'=>-1,
'msg' => '获取数据失败,请稍后重试...'
);
echo json_encode($ret);
}
/**本文以百度搜索suggestion返回的jsonp数据为例,模拟返回json数据的网站**/