我编写了一个 Javascript 方法,它从客户端浏览器向我们用 PHP 编写的 API 发送跨域 POST 请求:
$.ajax({
type: 'POST',
url: backend_url,
data: postArgs,
beforeSend: function( xhr, settings ) {
xhr.setRequestHeader( 'Connection', 'close' );
},
error: function( xhr, status, errorThrown ) {
console.log( 'RECONTRIBUTION: Error on AJAX request! status=' + status + ', errorThrown=' + errorThrown + ', statusText=' + xhr.statusText );
$( '#alert_message' ).showAlertMsg( 'error', 'Oops, we couldn\'t talk to our server! Please try again in a moment.' );
},
success: function( data, status, response ) {
//do things
}
});
在 Firefox、Chrome 和 Safari 中一切正常,但在 IE9 中我遇到了问题。第一个问题是我收到“无传输”错误,我认为这是由 IE 对跨域请求的限制引起的。通过将 jQuery.support.cors 设置为 true 并包含此插件,我得到了通过的请求,该插件在不同的 SO 线程上找到:https ://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest/blob/master/jQuery .XDomainRequest.js
现在请求已完成,但 API 返回错误,因为缺少请求正文。
来自 Chrome 的工作请求(网址已编辑):
POST [backendurl] HTTP/1.1
Host: [backendurl]
Connection: keep-alive
Content-Length: 79
Origin: [frontendurl]
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Accept: */*
Referer: [frontendurl]
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
DNT: 1
action=contributeSong&client=TUNEBOT&iTunes_id=17344380&user_id=&query_id=64600
来自 IE9 的非工作请求:
POST [backendurl] HTTP/1.1
Accept: */*
Origin: [frontendurl]
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Host: [backendurl]
Content-Length: 0
Connection: Keep-Alive
Pragma: no-cache
奇怪的是,我尝试将 Connection 标头设置为 Close,因为我读到 Keep-Alive 有时会导致 Internet Explorer 出现问题......但请求正在发送 Connection: Keep-Alive 无论如何。有任何想法吗?这几天我一直在扯头发。
更新:好的,所以在对 XDR 对象进行了更多阅读之后,我意识到我无法发送自定义标头,这解释了 Keep-Alive 问题。我查看了插件,它没有向服务器发送任何数据(...),所以现在我收到了 APPEARS 发送数据的请求,但仍然得到相同的响应......
POST [backendurl] HTTP/1.1
Accept: */*
Origin: [frontendurl]
Accept-Language: en-US
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Host: [backendurl]
Content-Length: 79
Connection: Keep-Alive
Pragma: no-cache
action=contributeSong&client=TUNEBOT&iTunes_id=23148795&user_id=&query_id=64612
如下所示,添加cache:false
选项似乎没有任何影响。是Connection:Keep-Alive
什么在杀死我?