如何从javascript读取cookie并在body onload时将其显示在下一页(Result.jsp)中

时间:2014-01-28 14:17:48

标签: javascript jsp

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="JavaScript/CommonJS.js">
    </script>
</head>
<body bgcolor="pink">    
    <div align="center" >
        <h1> <font color="red" >JavaScript task</font></h1>
    </div>

    <div  align="left" style="font-family:Verdana; font-size:13px">
        Number of Characters Left:
        <label id="lblcount" style="background-color:#E2EEF1;
                   color:Red;font-weight:bold;">100</label><br/>
        <textarea style="overflow:auto;resize:none" id="mytextbox" 
              rows="4" cols="50" maxlength="100" wrap="hard"
          onkeyup="LimtCharacters(this,100,'lblcount');"></textarea>
    </div>           

    <p align="center">
        <input type="button" id="view" name="view" 
               value="Next" onclick="SaveData()">               
    </p>         
</body>

这是我的index.jsp页面,当我点击下一个按钮它将转到CommonJS.js(javascript)那里我将数据保存在cookie中并转发到Result.jsp,在Result.jsp页面中如何我可以阅读cookie并将其显示在我的resul.jsp页面

Javascript是:

function LimtCharacters(txtMsg, CharLength, indicator) {
var chars = txtMsg.value.length;
document.getElementById(indicator).innerHTML = CharLength - chars;
if (chars > CharLength) {
    txtMsg.value = txtMsg.value.substring(0, CharLength);
}
}

function createCookie(cname,cvalue,exdays) {
if (exdays) {
    var date = new Date();
    date.setTime(date.getTime()+(exdays*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = cname+"="+cvalue+expires+";path=/";   
}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0)
        return c.substring(nameEQ.length,c.length);
}
return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

任何人都提前感谢我。

1 个答案:

答案 0 :(得分:1)

您可以使用body onload =“functioncall()”指令在加载时调用函数。要显示它,一个简单的方法是在页面中使用一个div来填充JavaScript中的cookie值。

代码如下所示:

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <script type="text/javascript">
    function displayCookie() {
      document.getElementById('myDiv').innerHTML = readCookie('myCookie');
    }
  </script>
</head>
<body onload="displayCookie()">    
  <div id="myDiv" ></div>
</body>