如何从不同的域饼干PHP和JavaScript [英] how to get cookies from a different domain with php and javascript
问题描述
假设我有一个cookie集first.com说用户。现在,我想读的second.com该Cookie通过JavaScript和Ajax。但它不是working.I已经得到xmlHttp.status = 0。
样品code
在第二个领域readcookie.php文件
VAR XMLHTTP;
功能createXMLHtt prequest(){
如果(window.ActiveXObject)
XMLHTTP =新的ActiveXObject(Microsoft.XMLHTTP);
如果(window.XMLHtt prequest)
XMLHTTP =新XMLHtt prequest();
}
功能readcookie(){
createXMLHtt prequest();
xmlHttp.open(GET,http://www.first.com/cookie.php,真正的);
xmlHttp.onreadystatechange =的getCookie;
xmlHttp.send(空);
}
功能的getCookie(){
如果(xmlHttp.readyState == 4){
如果(xmlHttp.status == 200){
VAR回复= xmlHttp.responseText;
如果(回复){
警报(答复);
}
}
其他
警报(xmlHttp.status);
}
}
在第一个域cookie.php文件
如果(使用isset($ _ COOKIE ['用户'])){
回声$ _COOKIE ['用户'];
}
其他{
的setcookie('用户','A2345,0);
回声$ _COOKIE ['用户'];
}
您不能从另一个域读取cookies - 结束
我能想到的唯一的办法就是增加一些code到第2域获取饼干给你,然后把这个在页面上的第一个域,iframe中。
您显然需要完全访问两个域能够做这种事情。
Suppose i have a cookie set in first.com say user. Now i want to read that cookie in second.com through javascript and ajax. But it is not working.I have got xmlHttp.status=0.
sample code
in the second domain readcookie.php file
var xmlHttp;
function createXMLHttpRequest(){
if(window.ActiveXObject)
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
if(window.XMLHttpRequest)
xmlHttp=new XMLHttpRequest();
}
function readcookie(){
createXMLHttpRequest();
xmlHttp.open("GET","http://www.first.com/cookie.php",true);
xmlHttp.onreadystatechange=getcookie;
xmlHttp.send(null);
}
function getcookie(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
var reply=xmlHttp.responseText;
if(reply){
alert(reply);
}
}
else
alert(xmlHttp.status);
}
}
in the first domain cookie.php file
if(isset($_COOKIE['user'])){
echo $_COOKIE['user'];
}
else{
setcookie('user','a2345',0);
echo $_COOKIE['user'];
}
You can't read cookies from another domain - end of.
The only way I can think of is to add some code to the 2nd domain that gets the cookies for you and then to place this in a page on the 1st domain, in an iframe.
You obviously need full access to both domains to be able to do this kind of thing.
这篇关于如何从不同的域饼干PHP和JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!