用js取得php生成的cookie

 1.php

<?php
  header("content-type:text/html;charset=gb2312");
  session_start();
  setcookie("username","test",time()+3600*24);
  $value = "my cookie value";
  // 发送一个 24 小时候过期的 cookie
  setcookie("TestCookie",$value, time()+3600*24);
  echo $_COOKIE["username"]."<br/>";
  echo $_COOKIE["TestCookie"];
  $_SESSION["username"]="test115";
?>

2.php

<?
header("content-type:text/html;charset=gb2312");
session_start();
echo $_COOKIE["username"];
echo $_SESSION["username"];
?>
<script language=javascript>
function getCookie(cookie_name)
{
var allcookies = document.cookie;
var cookie_pos = allcookies.indexOf(cookie_name);

// 如果找到了索引,就代表cookie存在,
// 反之,就说明不存在。
if (cookie_pos != -1)
{
// 把cookie_pos放在值的开始,只要给值加1即可。
cookie_pos += cookie_name.length + 1;
var cookie_end = allcookies.indexOf(";", cookie_pos);

if (cookie_end == -1)
{
cookie_end = allcookies.length;
}

var value = unescape(allcookies.substring(cookie_pos, cookie_end));
}

return value;
}

alert(getCookie("username"));
</script>

    A+
发布日期:2021年07月14日  所属分类:未分类

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: