jQuery 跨域 jsonp 的基本操作方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5463256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Basic how-to for cross domain jsonp
提问by user581733
I looked everywhere here for this. I need just a simple "how-to" pull jsonp cross domain. I'm using jQuery 1.5.1.
我到处找这个。我只需要一个简单的“操作方法”拉 jsonp 跨域。我正在使用 jQuery 1.5.1。
I tried the following in a program on another site:
我在另一个站点的程序中尝试了以下操作:
$.getJSON("http://www.mydomain.com/testjson.json?jsoncallback=?", function(data) {
alert("I'm hitting this.");
}
This doesn't work at all.
这根本行不通。
Is there a way of just doing a simple cross domain jquery JSONP call?
有没有办法只做一个简单的跨域 jquery JSONP 调用?
Thanks
谢谢
回答by Matt
JSONP requires the cooperation of the server to succeed. You cannot pull random pages using JSONP and expect them to succeed; the server needs to know:
JSONP 需要服务器的配合才能成功。您不能使用 JSONP 随机抽取页面并期望它们成功;服务器需要知道:
- It needs to formulate a JSONP response, rather than a JSON response.
- It needs to know the name of the function to wrap the response around.
- 它需要制定 JSONP 响应,而不是 JSON 响应。
- 它需要知道函数的名称来包装响应。
If you're unsure on why the server needs to know these, or what the differences are between JSON and JSONP, you should read up on them; or the whole thing will make no sense. For starters, check out Can anyone explain what JSONP is, in layman terms?and http://en.wikipedia.org/wiki/JSONP.
如果你不确定为什么服务器需要知道这些,或者 JSON 和 JSONP 之间有什么区别,你应该阅读它们;否则整件事就毫无意义。对于初学者,请查看任何人都可以用外行术语解释什么是 JSONP?和http://en.wikipedia.org/wiki/JSONP。
After understanding this a little more, you'll probably find the server is returning
多了解一点后,您可能会发现服务器正在返回
{ "key": 1, "bar": "foo" }
(which is valid JSON), rather than:
(这是有效的 JSON),而不是:
someCallback({ "key": 1, "bar": "foo" })
which is a JSONP response.
这是一个 JSONP 响应。
回答by vitralyoz
If you try these http://terrasus.com/detail.jsp?articleID=396step by step it will work fine. if you produce jsonp response you should get the callback value and set it to your response dynamically. This article has a detail explanation
如果您逐步尝试这些http://terrasus.com/detail.jsp?articleID=396,它将正常工作。如果您生成 jsonp 响应,您应该获取回调值并将其动态设置为您的响应。这篇文章有详细解释