当服务器不支持响应回调函数时,这种使用 JSONP 的跨域调用是否有效?
我希望使用 jQuery 进行跨域调用,并通过查询字符串传递参数来触发服务器执行操作(例如发送电子邮件、后台打印作业、启动咖啡机)。 我的问题是服务器不支持 JSONP 响应*,并且在我的时间范围内更改它是不可行的。
假设我的页面托管在 http://foo.com /test.htm
并且跨域调用正在 http://bar 处的 Web 服务进行.com/service.svc`。启动电子邮件作业的 URL 如下(这完全是虚构的):
var mailerUrl = "http://bar.com/service.svc?job=email&to=fred&type=outage";
经过思考,我想知道服务器不支持 JSONP 响应是否真的很重要,因为对 < code>mailerUrl 足以开始工作。
jQuery 代码将是这样的(我认为):
$.getJSON(mailerUrl + "&callback=?", function (json) { });
服务器将使用此 JSON 进行响应:
{ "d": { "EmailJob": true } }
请注意,响应没有包装在回调函数中。
jQuery 代码在收到响应后最终会失败,因为它不是 JSONP 格式。
然而,我想知道这是否会在所有主要的现代浏览器(IE9、Chrome、Firefox4+ 和 Safari4+)中成功跨域?
I'm looking to do a cross-domain call with jQuery and passing parameters via query string to trigger the server to do an action (e.g. send an email, spool up a print job, start the coffee maker). My problem is that the server doesn't support JSONP responses* and it's not feasible in my time frame to get it changed.
Assume that my page is hosted in http://foo.com/test.htm
and the cross domain call is being made to a web-service at http://bar.com/service.svc`. The URL to kick off an email job is as follows (this is totally fictitious):
var mailerUrl = "http://bar.com/service.svc?job=email&to=fred&type=outage";
After thinking about it, I'm wondering whether it actually matters that the server doesn't support JSONP responses since the GET request to the mailerUrl
is enough to kick the job off.
The jQuery code would be this (I think):
$.getJSON(mailerUrl + "&callback=?", function (json) { });
The server will respond with this JSON:
{ "d": { "EmailJob": true } }
Notice that the response isn't wrapped in a callback function.
The jQuery code ends up bailing after it gets the response since it's not in JSONP format.
However, what I'm wondering is will this succeed cross domain in all the major modern browsers (IE9, Chrome, Firefox4+ and Safari4+)?
答案是:不。试想一下,任何网站都可以仅仅因为您登录就从您的 Gmail 帐户加载 JSON 数据 - 这很糟糕,对吧?因此,浏览器会正确地阻止您跨域读取 JSON 数据,除非目标允许(通过 CORS 或支持回调)。
如果唯一的一点是发送跨域 GET 请求而不接收任何数据,那么 new Image().src = "http://..." 是更简单的方法。
The answer is: no. Just imagine that any website could load JSON data from your Gmail account just because you are logged in - would be bad, right? So browsers rightfully prevent you from reading JSON data across domains unless the target allows it (via CORS or by supporting a callback).
If the only point is sending a cross-domain GET request without receiving any data then
new Image().src = "http://..."
is the easier way.