简体   繁体   English

当服务器不支持回调功能时,使用JSONP进行跨域调用是否可以工作?

[英]Will this cross-domain call with JSONP work when server doesn't support callback function in response?

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 (eg send an email, spool up a print job, start the coffee maker). 我正在尝试使用jQuery进行跨域调用,并通过查询字符串传递参数以触发服务器执行某项操作(例如,发送电子邮件,后台打印任务,启动咖啡壶)。 My problem is that the server doesn't support JSONP responses* and it's not feasible in my time frame to get it changed. 我的问题是服务器不支持JSONP响应*,并且在我的时间范围内更改它是不可行的。

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 `. 假设我的页面托管在http://foo.com/test.htm并且跨域调用是通过http://bar.com/service.svc`进行的Web服务调用。 The URL to kick off an email job is as follows (this is totally fictitious): 启动电子邮件工作的URL如下(这完全是虚构的):

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. 考虑一下之后,我想知道服务器不支持JSONP响应是否真的很重要,因为对mailerUrl的GET请求足以启动该工作。

The jQuery code would be this (I think): jQuery代码是这样的(我认为):

$.getJSON(mailerUrl + "&callback=?", function (json) { });

The server will respond with this JSON: 服务器将使用以下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. jQuery代码在获得响应后最终会失败,因为它不是JSONP格式。

However, what I'm wondering is will this succeed cross domain in all the major modern browsers (IE9, Chrome, Firefox4+ and Safari4+)? 但是,我想知道的是,这种跨域功能能否在所有主要的现代浏览器(IE9,Chrome,Firefox4 +和Safari4 +)中成功实现?

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? 试想一下,仅因为您已登录,任何网站都可以从您的Gmail帐户加载JSON数据-不好吗? So browsers rightfully prevent you from reading JSON data across domains unless the target allows it (via CORS or by supporting a callback). 因此,浏览器正确地阻止您跨域读取JSON数据,除非目标允许(通过CORS或通过支持回调)。

If the only point is sending a cross-domain GET request without receiving any data then new Image().src = "http://..." is the easier way. 如果唯一的问题是发送跨域GET请求而不接收任何数据,则new Image().src = "http://..."是更简单的方法。

This should work, you won't be able to do anything with the response, it will likely just be evaluated and thrown away. 这应该可行,您将无法对响应做任何事情,它可能会被评估并丢弃。 But if you just want to invoke a service on the remote server there is no reason why this wouldn;t work 但是,如果您只想在远程服务器上调用服务,则没有理由不起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM