跨域的XMLHttpRequest读取COOKIE

时间:2013-01-22 01:28:32

标签: php javascript cross-domain

亲爱的,我有一个奇怪的问题。

我的目标是:    网站 abc.com 会向网站 xyz.com

发送ajax' POST / GET '请求

xyz.com 将通过PHP创建 COOKIE 并打印出来:

print $_COOKIE["rand_user_id"];

所以网站 abc.com 会通过“ xhr.responseText ”读取打印的文本。

PS:即使刷新了页面,xhr.responseText也会打印相同的文本。

问题:所有条款说明都可以正常使用

但JavaScript希望能够打印出内容文本!

xhr.status 返回0 !!!!

当我通过HTTPAnalyze嗅探响应时,我可以在responseText的内容中看到TEXT。 HTTPAnalyze程序中的响应代码为200。

请咨询


我的代码是:

客户端

    <script>
window.onload = function(){
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://www.adriper.com/setcookie.php", true);
    xhr.onreadystatechange = function(){
        if ( xhr.readyState == 4 ) {
            if ( xhr.status == 200 ) {
                document.body.innerHTML = "Random code  is: " + xhr.responseText;
            } else {
                document.body.innerHTML = "ERROR Number :"+xhr.status;
            }
        }
    };

    xhr.withCredentials = true; 
    xhr.send(null);
};
</script>

服务器端是:

PHP

<?
if(!isset($_COOKIE["rand_user_id"]))
{
   $val = md5(rand(111,999));   
   setcookie("rand_user_id", $val , time()+60*60*24*30, '/');
   print $_COOKIE["rand_user_id"];
}else{
    print $_COOKIE["rand_user_id"];
    }
?>

的.htaccess

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type ,accept"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Header add Access-Control-Allow-Credentials: true

HTTP响应

GET /setcookie.php HTTP/1.1
Host: www.adriper.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:18.0) Gecko/20100101 Firefox/18.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost/mouse/Untitled-1.html?w
Origin: http://localhost
Cookie: rand_user_id=m3zwy_pomRVe1FovfsOXBLJvUyw_lnA6MWMjot1lSGtXB3MwGXJlR0d2afbxwBWe
Connection: keep-alive

选项

HTTP/1.1 200 OK
Server: nginx
Date: Tue, 22 Jan 2013 00:55:30 GMT
Content-Type: text/html
Connection: keep-alive
X-Powered-By: PHP/5.2.17
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: origin, x-requested-with, content-type ,accept
Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS
Access-Control-Allow-Credentials: true
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 52

0 个答案:

没有答案