jQuery和跨域POST请求 [英] jQuery and Cross Domain POST Requests

查看:222
本文介绍了jQuery和跨域POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个jQuery插件,它将成为某些REST API的连接器。
实施很简单,但同样的原产地政策肯定是痛苦的。
我需要主要执行POST请求。

I'm developing a jQuery plug-in that will be a connector for some REST API. The implementation is straight forward, but the same origin policy is definitely painfull. I need to perform mostly POST requests.

我还试图实现OPTIONS方法并返回(是python,但意思应该是明确的)

I also tried to implement the OPTIONS method and returning (is python, but the meaning should be clear)

def options(self):
  self.response.headers['Access-Control-Allow-Origin'] = self.request.host_url
  self.response.headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
  self.response.headers['Access-Control-Allow-Headers'] = 'x-requested-with'
  self.response.headers['Access-Control-Max-Age'] = '1728000'

仍然不起作用......任何想法?

still doesn't work... any idea ?

PS:我看到还有其他问题一个类似的主题,但我需要POST方法的特定解决方案(GET可以通过使用iframe轻松实现)

PS: I have seen that there are other question with a similar topic but i need a specific solution for POST method (GET could be easely implemented by using iframes)

Javascript示例:

Javascript example:

$.ajax({
    url: options.protocol+'://'+options.host+':'+options.port+'/'+method,
    data: rawData,
    async:false,
    dataType: "json",
    type:"POST",
    success:function(data)
    {
        alert('asd');
        result.data = data;
        alert(data);
    },
    error:function(lol){
        alert('omggg !!!!'+lol);
    }

});

编辑:添加了javascript代码示例

added javascript code example

推荐答案

有时候这是一个小提琴,一些想法:

It's a bit of a fiddle sometimes, some thoughts:


  • CORS只有相当现代的支持浏览器,所以你需要确保你正在使用其中一个。

  • IE仅通过 XDomainRequest 对象,而非标准 XMLHttpRequest 对象,但jQuery没有特别满足(但是我必须承认我有点惊讶,并且期望它会在太长时间之前),所以你必须添加特殊处理才能使这个工作在IE上(然后只有IE8及以上版本)。 编辑:令人震惊的是,显然jQuery团队已经收到了该请求并且拒绝票#8283 这使 没有 感觉。

  • 您确定 Access-Control-Allow-Origin 值? 看起来就像它只允许从服务器访问它一样。该标头用于指定服务器允许来自来自的请求的起源。 (而且 * 是允许的,意思是在任何地方。)

  • 我似乎记得我在Firefox上的实验,它是在回复它没有要求的 OPTIONS 请求时,我对允许的方法很挑剔。

  • 仔细检查你的'允许所有请求发送的标头;在你的例子中,你似乎只允许一个标题( x-requested-with ),但我打赌在实际请求中会有其他标题。

  • CORS is only supported by fairly modern browsers, so you'll need to be sure you're using one of those.
  • IE only supports CORS via the XDomainRequest object, not the standard XMLHttpRequest object, but jQuery doesn't specifically cater for that (yet; I have to admit I'm slightly surprised and expect it will before too long), so you have to add special handling to make this work on IE (and then only IE8 and above). Edit: Shockingly, apparently the jQuery team have had that request and denied it: ticket #8283 That makes no sense.
  • Are you sure about that Access-Control-Allow-Origin value? It looks like it's only allowing access from the server it's on. That header is meant to specify what origins the server will allow the request to come from. (And * is allowed, to mean "anywhere.")
  • I seem to recall from my experiments with Firefox on this that it was finicky about my allowing methods when responding to the OPTIONS request that it hadn't asked for.
  • Double-check that you're allowing all of the headers that the request is sending; in your example it looks like you're only allowing one header (x-requested-with), but I bet there will be others in the actual request.

FWIW(我不是Python人),这是我的JSP代码可行,也许它会很有用 —我认为对象名称足够清晰,即使你不做Java也是可读的(谁知道,也许你这样做):

FWIW (I'm not a Python guy), here's my JSP code that works, perhaps it will be useful — I think the object names are clear enough to be readable even if you don't do Java (and who knows, maybe you do):

String corsOrigin, corsMethod, corsHeaders;

// Find out what the request is asking for
corsOrigin = request.getHeader("Origin");
corsMethod = request.getHeader("Access-Control-Request-Method");
corsHeaders = request.getHeader("Access-Control-Request-Headers");
if (corsOrigin == null || corsOrigin.equals("null")) {
    // Requests from a `file://` path seem to come through without an
    // origin or with "null" (literally) as the origin.
    // In my case, for testing, I wanted to allow those and so I output
    // "*", but you may want to go another way.
    corsOrigin = "*";
}

// Add headers allowing specifically what was requested
response.addHeader("Access-Control-Allow-Origin", corsOrigin);
response.addHeader("Access-Control-Allow-Methods", corsMethod);
response.addHeader("Access-Control-Allow-Headers", corsHeaders);
if (request.getMethod().equals("OPTIONS"))
{
    // Done, no body in response to OPTIONS
    return;
}
// Processing the GET or POST here; output the body of the response

请注意,我对<$ c $使用完全相同的逻辑c> GET , POST OPTIONS ,但在OPTIONS的情况下,我不输出回复正文。

Note that I'm using exactly the same logic for GET, POST, and OPTIONS except that in the case of OPTIONS, I don't output a response body.

这篇关于jQuery和跨域POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆