我如何设置JSONP? [英] How do I set up JSONP?
问题描述
我需要在服务器端允许某人使用JSONP从该服务器获取数据。我还需要在用户方面做些什么?我想使用JSONP作为XMLHttpRequest的替代方法。
由于同源策略,它不能用于我的Firefox扩展。所以,人们推荐JSON,但是在网上搜索教程和指南后,我迷上了。
感谢您的帮助!
<假设你的服务器正在运行PHP,你只需要添加'callback'GET请求。
<$ p $
<?php header('content-type:application / json; charset = utf-8');
$ data = array('a'=> 1,'b'=> 2,'c'=> 3,'d'=> 4,'e'=> 5)。
echo $ _GET ['callback']。 ( .json_encode($数据)。);
而在客户端(使用jQuery):
$。ajax({url:'http://site.com/data.php',dataType:'jsonp'});
上面的PHP代码仅供演示,不要忘了 sanitize $ _GET ['callback']
这就是说,如果你的问题只是相同的来源政策,你可能只需要允许交叉来源从服务器端,一切都应该工作。
What do I need to on the server side to allow someone to get data from that server using JSONP. And what do I need to do on the user side as well? I want to use JSONP as an alternative to an XMLHttpRequest.
It won't work out of my Firefox extension, because of the same-origin policy. So, people recommended JSON, but I am pretty lost after searching for tutorials and guides on the internet.
Thanks for the help!
Assuming your server is running PHP, you just need to add 'callback' GET request.
<?php header('content-type: application/json; charset=utf-8');
$data = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo $_GET['callback'] . '('.json_encode($data).')';
And on client side (using jQuery):
$.ajax({url: 'http://site.com/data.php', dataType:'jsonp'});
The PHP code above is just for demo, don't forget to sanitise $_GET['callback']
That said, if your issue just the same origin policy, you'll probably just need to allow cross-origin from the server side, and everything should work.
这篇关于我如何设置JSONP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!