問題描述
我有這個代碼:
window.onload = function() {
document.cookie = 'foo=bar; expires=Sun, 01 Jan 2012 00:00:00 +0100; path=/';
var xhr = new XMLHttpRequest();
xhr.open("GET", "/showcookie.php",true);
xhr.setRequestHeader("Cookie", "foo=quux");
xhr.setRequestHeader("Foo", "Bar");
xhr.setRequestHeader("Foo", "Baz");
xhr.withCredentials = true;
var pre = document.getElementById('output');
xhr.onreadystatechange = function() {
if (4 == xhr.readyState) {
pre.innerHTML += xhr.responseText + "
";
}
};
xhr.send(null);
};
還有這個/showcookie.php
and this /showcookie.php
<?php
print_r($_COOKIE);
?>
它總是顯示
Array
(
[Host] => localhost
[User-Agent] =>
[Accept] =>
[Accept-Language] => pl,en-us;q=0.7,en;q=0.3
[Accept-Encoding] => gzip,deflate
[Accept-Charset] => ISO-8859-2,utf-8;q=0.7,*;q=0.7
[Keep-Alive] => 115
[Connection] => keep-alive
[foo] => Baz
[Referer] =>
[Cookie] => foo=bar
)
Array
(
[foo] => bar
)
我在 Ubuntu 上使用 Firefox 3.6.13、Opera 11.00 和 Chromium 9.0.
I'm using Firefox 3.6.13, Opera 11.00 and Chromium 9.0 on Ubuntu.
有沒有人有同樣的問題,或者無法修改 Cookie 標頭.
Is anybody have the same problem or maybe it's impossible to modify Cookie header.
推薦答案
Cookie 標頭是 XMLHttpRequest
中無法修改的幾個標頭之一.來自規(guī)范:
The Cookie header is one of several which cannot be modified in an XMLHttpRequest
. From the specification:
終止[執(zhí)行setRequestHeader
方法]如果header是一個不區(qū)分大小寫的匹配項之一以下標題:
Terminate [execution of the
setRequestHeader
method] if header is a case-insensitive match for one of the following headers:
- 接受字符集
- 接受編碼
- 連接
- 內容長度
- Cookie
- Cookie2
- 內容傳輸編碼
- 日期
- 期待
- 主持人
- 保持活躍
- 推薦人
- TE
- 預告片
- 傳輸編碼
- 升級
- 用戶代理
- 通過
... 或者如果標題的開頭是代理的不區(qū)分大小寫匹配 - 或Sec- (包括當標題只是Proxy-或Sec-).
… or if the start of header is a case-insensitive match for Proxy- or Sec- (including when header is just Proxy- or Sec-).
以上標題由用戶代理讓它控制那些運輸方面.這保證數據完整性在一定程度上.標題以 Sec- 開頭的名稱不是允許設置為允許新標頭保證不會被鑄造來自 XMLHttpRequest.
The above headers are controlled by the user agent to let it control those aspects of transport. This guarantees data integrity to some extent. Header names starting with Sec- are not allowed to be set to allow new headers to be minted that are guaranteed not to come from XMLHttpRequest.
這篇關于如何從 Ajax 調用修改 Cookie的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!