小编典典

CORS POST请求可在普通JavaScript上运行,但是为什么不使用jQuery?

javascript

我正在尝试发出跨源发帖请求,并且使它JavaScript像下面这样简单地工作:

var request = new XMLHttpRequest();
var params = "action=something";
request.open('POST', url, true);
request.onreadystatechange = function() {if (request.readyState==4) alert("It worked!");};
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);

但是我想使用jQuery,但是我无法使用它。这是我正在尝试的:

$.ajax(url, {
    type:"POST",
    dataType:"json",
    data:{action:"something"}, 
    success:function(data, textStatus, jqXHR) {alert("success");},
    error: function(jqXHR, textStatus, errorThrown) {alert("failure");}
});

这导致失败。如果有人知道为什么jQuery不起作用,请告诉我们。谢谢。

(我正在使用jQuery1.5.1和Firefox 4.0,并且我的服务器使用正确的Access-Control-Allow- Origin标头进行响应)


阅读 318

收藏
2020-05-01

共1个答案

小编典典

更新:正如TimK所指出的,jQuery 1.5.2不再需要此功能。但是,如果要添加自定义标题或允许使用凭据(用户名,密码或cookie等),请继续阅读。


我想我找到了答案!(4小时后又进行了很多诅咒)

//This does not work!!
Access-Control-Allow-Headers: *

您需要手动指定将接受的所有标头(至少在FF 4.0和Chrome 10.0.648.204中,这是我的情况)。

jQuery的$ .ajax方法为所有跨域请求发送“ x-requested-with”标头(我认为这是唯一的跨域)。

因此,响应OPTIONS请求所需的缺少标头是:

//no longer needed as of jquery 1.5.2
Access-Control-Allow-Headers: x-requested-with

如果要传递任何非“简单”标头,则需要将它们包括在列表中(我再发送一个):

//only need part of this for my custom header
Access-Control-Allow-Headers: x-requested-with, x-requested-by

综上所述,这是我的PHP:

// * wont work in FF w/ Allow-Credentials
//if you dont need Allow-Credentials, * seems to work
header('Access-Control-Allow-Origin: http://www.example.com');
//if you need cookies or login etc
header('Access-Control-Allow-Credentials: true');
if ($this->getRequestMethod() == 'OPTIONS')
{
  header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
  header('Access-Control-Max-Age: 604800');
  //if you need special headers
  header('Access-Control-Allow-Headers: x-requested-with');
  exit(0);
}
2020-05-01