如何修改Ajax调用的Cookie [英] How to modify Cookie from Ajax call

查看:100
本文介绍了如何修改Ajax调用的Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

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 + "\n";
            }
        };
        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
)

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 中修改的其中一个。从规范

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


终止 [ setRequestHeader 方法的执行] if header is a
case-insensitive match for one of
以下标头:

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


  • Accept-Charset

  • 接受编码

  • 连接

  • 内容长度

  • Cookie

  • Cookie2

  • 内容转移编码

  • 日期

  • 期望

  • / li>
  • 保持活动

  • 参照

  • TE

  • / li>
  • 传输编码

  • 升级

  • User-Agent

  • 通过

  • 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

...或者如果标题的开头是
代理或$ b不区分大小写匹配 - (包括当头只是
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆