发送跨域信息的凭据?

根据 带证件的请求的规定,只有在下列情况下,Firefox 才会发送凭证和跨域帖子

invocation.withCredentials = "true";

但是看起来 jQuery 的 Ajax API 并没有为此提供任何机制。

我是不是错过了什么? 还有别的办法吗?

164729 次浏览

You can use the beforeSend callback to set additional parameters (The XMLHTTPRequest object is passed to it as its only parameter).

Just so you know, this type of cross-domain request will not work in a normal site scenario and not with any other browser. I don't even know what security limitations FF 3.5 imposes as well, just so you don't beat your head against the wall for nothing:

$.ajax({
url: 'http://bar.other',
data: { whatever:'cool' },
type: 'GET',
beforeSend: function(xhr){
xhr.withCredentials = true;
}
});

One more thing to beware of, is that jQuery is setup to normalize browser differences. You may find that further limitations are imposed by the jQuery library that prohibit this type of functionality.

Functionality is supposed to be broken in jQuery 1.5.

Since jQuery 1.5.1 you should use xhrFields param.

$.ajaxSetup({
type: "POST",
data: {},
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true
});

Docs: http://api.jquery.com/jQuery.ajax/

Reported bug: http://bugs.jquery.com/ticket/8146

In jQuery 3 and perhaps earlier versions, the following simpler config also works for individual requests:

$.ajax(
'https://foo.bar.com,
{
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: successFunc
}
);

The full error I was getting in Firefox Dev Tools -> Network tab (in the Security tab for an individual request) was:

An error occurred during a connection to foo.bar.com.SSL peer was unable to negotiate an acceptable set of security parameters.Error code: SSL_ERROR_HANDSHAKE_FAILURE_ALERT