跨站点使用jQuery AJAX [英] Cross-site AJAX using jQuery
问题描述
我有一个现有的jQuery插件,这让很多AJAX调用(主要是JSON)的。我想知道什么是最快的,以允许它做跨站点的呼叫即$不用彷徨和$。员额的URL将无法从同一个域。
我听说JSONP的,但不知道是否有人可以给我一个具体的例子去了解整个过程。我想给我的脚本使可能的话最小的变化。我应该使用各种各样的proxy.php?
感谢您的时间。
JSONP可以让你做跨站点调用。 见就这一问题jQuery的文档。
这个概念很简单:而不是做一个正常的Ajax调用,jQuery将追加<脚本>
标记的< HEAD>
。为了使这项工作,需要你的JSON数据被包裹在一个
函数调用。
您的服务器需要以这样的方式发送的信息(例如PHP):
$ JSON = json_en code($的数据);
回声$ _GET ['jsonp_callback']。 (。$ JSON。');';
然后,您可以使用jQuery来获取这些信息:
$。阿贾克斯({
数据类型:JSONP,
JSONP:jsonp_callback,
网址:http://myotherserver.com/getdata,
成功:函数(){
//做的东西
},
});
的更多信息,请访问:什么是JSONP <? / P>
I have an existing jQuery plugin which makes a lot of AJAX calls (mostly JSON). I am wondering what is the quickest to allow it to do cross-site calls i.e. the $.get and $.post URL's will not be from the same domain.
I have heard of JSONP, but was wondering if someone could give me an concrete example to go about the whole process. I want to make minimal changes if possible to my script. Should I use a proxy.php of sorts?
Thank you for your time.
JSONP will allow you to do cross-site calls. See jQuery docs on that matter.
The concept is simple: instead of doing a normal Ajax call, jQuery will append a <script>
tag to your <head>
. In order for this to work, your JSON data needs to be wrapped in a
function call.
Your server needs to send information in such way (PHP example):
$json = json_encode($data);
echo $_GET['jsonp_callback'] . '(' . $json . ');';
Then, you can use jQuery to fetch that information:
$.ajax({
dataType: 'jsonp',
jsonp: 'jsonp_callback',
url: 'http://myotherserver.com/getdata',
success: function () {
// do stuff
},
});
More information is available here: What is JSONP?
这篇关于跨站点使用jQuery AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!