2012-04-05 43 views
1

我有两个HTML文件。一个文件需要将标题发送到第二个文件。 第二个文件需要收到标题和alert()它。 我需要更改代码以根据需要运行?如何通过cookie使用js发送参数

cookieTitleSend.html

<html> 
<head> 
<script type="text/javascript"> 

function setCookie(Title_name,value,exdays) 
{ 
var exdate=new Date(); 
exdate.setDate(exdate.getDate() + exdays); 
var Title_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); 
document.cookie=Title_name + "=" + Title_value; 
} 
</script> 
</head> 
<body onload="setCookie("Title_name",PHP Hello World,1);"> 
</body> 
</html> 

cookieTitleReceive.html

<html> 
<head> 
<script type="text/javascript"> 
function getCookie(Title_name) 
{ 
var i,x,y,ARRcookies=document.cookie.split(";"); 
for (i=0;i<ARRcookies.length;i++) 
    { 
    x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); 
    y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); 
    x=x.replace(/^\s+|\s+$/g,""); 
    if (x==Title_name) 
    { 
    return unescape(y); 
    } 
    } 
} 

function checkCookie() 
{ 
var Title_name=getCookie("Title_name"); 
if (Title_name!=null && Title_name!="") 
    { 
    alert("Welcome again your Title is 
: " + Title_name); 
    } 
else 
    { 
    Title_name=prompt("There is no title :",""); 

    } 
} 
</script> 
</head> 
<body onload="checkCookie()"> 
</body> 
</html> 
+0

你用Firebug检查你的JavaScript是否设置了cookie? – hohner 2012-04-05 15:21:41

+0

嗨,我不知道如何检查萤火虫饼干。我会检查现在thx。 – 2012-04-05 15:37:41

回答

2

您的代码看起来有一些问题,但你可以用适当的布线事件处理程序启动。

<body onload="setCookie('Title_name','PHP Hello World',1);"> 
+0

我尝试不起作用。 – 2012-04-05 15:18:57

0

我想可能有一些细微的东西在你的代码,看看如何利用饼干this链接。也就是说,你的二传手可能需要做如下修改:

exdate.setTime(today.getTime() + 3600000*24*exDays); 
document.cookie = cookieName+"="+escape(value) 
      + ";expires="+exdate.toGMTString(); 

东西我在你的循环看到的getCookie:

for (i=0;i<ARRcookies.length;i++) 

,我认为应该是:

for (i=0;i<ARRcookies.length-1;i++) 

希望这有帮助!

-sf

+0

非常感谢。它不工作,我会再次尝试别的东西。 – 2012-04-05 15:38:59