我正在try 发出一个跨域发布请求,我让它像这样在普通的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,但我没法用.这就是我要try 的:

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

This results in Failure. If anyone knows why jQuery doesn't work, please let us all know. Thanks.

(我使用的是jQuery 1.5.1和Firefox 4.0,我的服务器使用的是正确的Access-Control-Allow-Origin头)

推荐答案

更新:正如TimK指出的,jQuery1.5.2不再需要这种功能.但是,如果您想添加自定义标题或允许使用凭据(用户名、密码或cookie等),请继续阅读.


I think I found the answer! (4 hours and a lot of cursing later)

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

您需要手动指定将接受的所有标题(至少在FF 4.0和Chrome 10.0.648.204中是这样).

jQuery的美元.ajax方法为所有跨域请求发送"x-request-with"头(我认为它是唯一的跨域请求).

So the missing header needed to respond to the OPTIONS request is:

//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

So to put it all together, here is my 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);
}

Jquery相关问答推荐

如何用each替换元素的attr href

如何向父元素添加类?

确定元素是否是其父元素的最后一个子元素

了解 Backbone.js REST 调用

Google Maps API v3 infowindow 关闭事件/回调?

如何使用 jQuery 清空输入值?

如何在 Jquery 中通过索引获取子元素?

聚焦 时防止 iphone 默认键盘

Bootstrap 3.0 弹出框和工具提示

检测用户是否创建了滚动事件

jQuery从字符串中删除'-'字符

Url.Action 在我的 url 中放了一个 &,我该如何解决这个问题?

如何通过jQuery函数仅获取直接子元素

jQuery:如何找到父母的特定子元素?

如何重新加载/刷新 jQuery 数据表?

更改 div 的内容 - jQuery

如何在按键事件后获取 jQuery .val()?

使用中键触发 onclick 事件

jQuery - 不可见时获取元素的宽度(显示:无)

使用 jQuery/Javascript 防止任何形式的页面刷新