Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

javascript - How to modify Cookie from Ajax call

I have this code:

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);
    };

and this /showcookie.php

<?php

print_r($_COOKIE);

?>

and it always show

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
)

I'm using Firefox 3.6.13, Opera 11.00 and Chromium 9.0 on Ubuntu.

Is anybody have the same problem or maybe it's impossible to modify Cookie header.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Cookie header is one of several which cannot be modified in an XMLHttpRequest. From the specification:

Terminate [execution of the setRequestHeader method] if header is a case-insensitive match for one of the following headers:

  • Accept-Charset
  • Accept-Encoding
  • Connection
  • Content-Length
  • Cookie
  • Cookie2
  • Content-Transfer-Encoding
  • Date
  • Expect
  • Host
  • Keep-Alive
  • Referer
  • TE
  • Trailer
  • Transfer-Encoding
  • Upgrade
  • User-Agent
  • Via

… or if the start of header is a case-insensitive match for Proxy- or Sec- (including when header is just Proxy- or Sec-).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...