jsonp

来源:互联网 发布:金蝶软件用户名 编辑:程序博客网 时间:2024/05/16 19:44

Jsonp(JSON with Padding) 是 json 的一种"使用模式",可以让网页从别的域名(网站)那获取资料,即跨域读取数据。

为什么我们从不同的域(网站)访问数据需要一个特殊的技术(JSONP )呢?这是因为同源策略。

同源策略,它是由Netscape提出的一个著名的安全策略,现在所有支持JavaScript 的浏览器都会使用这个策略。

JSONP 应用

1. 服务端JSONP格式数据

如客户想访问 : http://www.runoob.com/try/ajax/jsonp.php?jsonp=callbackFunction。

假设客户期望返回JSON数据:["customername1","customername2"]。

真正返回到客户端的数据显示为: callbackFunction(["customername1","customername2"])。

服务端文件jsonp.php代码为:

jsonp.php 文件代码

<?phpheader('Content-type: application/json');//获取回调函数名$jsoncallback = htmlspecialchars($_REQUEST['jsoncallback']);//json数据$json_data = '["customername1","customername2"]';//输出jsonp格式的数据echo$jsoncallback ."(" . $json_data .")";?>

客户端页面完整代码

<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>JSONP 实例</title></head><body><divid="divCustomers"></div>
<scripttype="text/javascript">
functioncallbackFunction(result,methodName){
varhtml ='<ul>';
for(vari =0;i <result.length;i++){
html +='<li>' + result[i] + '</li>';
}
html +='</ul>';
document.getElementById('divCustomers').innerHTML = html;}
</script>
<scripttype="text/javascript"src="http://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script></body></html>

jQuery 使用 JSONP

以上代码可以使用 jQuery 代码实例:

<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>JSONP 实例</title><scriptsrc="http://cdn.static.runoob.com/libs/jquery/1.8.3/jquery.js"></script></head><body><divid="divCustomers"></div>
<script>
$.getJSON("http://www.runoob.com/try/ajax/jsonp.php?jsoncallback=?",function(data){varhtml ='<ul>';
for(vari =0;i <data.length;i++){
html +='<li>' + data[i] + '</li>';
}
html +='</ul>';
$('#divCustomers').html(html);});
</script>
</body></html>
getJson的使用方法 jQuery.getJSON(url,[data],[callback])
要获得一个json文件的内容,就可以使用$.getJSON()方法,这个方法会在取得相应文件后对文件进行处理,并将处理得到的JavaScript对象提供给代码.

回调函数提供了一种等候数据返回的方式,而不是立即执行代码,回调函数也需要一个参数,该参数中保存着返回的数据。这样我们就可能使用jQuery提供的另一个全局函数(类方法).each()来实现循环操作,将.getJSON函数返回的每组数据循环处理。
原创粉丝点击