html 中如何读取cookie

html-css015

html 中如何读取cookie,第1张

//读取COOKIES

function getCookie(name)

{

var arr,reg=new RegExp("(^| )"+name+"=([^]*)(|$)")

if(arr=document.cookie.match(reg)) return unescape(arr[2])

else return null

}

var img = getCookie("xxx")

然后 document.getElementById("body").style.backgroundImage = img

PHP生成cookie,HTML页面使用JavaScript即可读取。操作示例如下:

<?php

//首先php生成cookie;

//demo.php

// 开启session

session_start()

$name="baiduzhidao"

setcookie("cname",$name,time()+3600,"/")

?>

2.HTML页面读取;

//index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "

<html xmlns="

<head>

<meta http-equiv="Content-Type" content="text/html charset=utf-8" />

<title>JS读取cookie示例</title>

<style>

body{ font-size:14px line-height:22px font-family:"微软雅黑", Verdana, Geneva, sans-serif}

input,textarea{ font-family:"微软雅黑", Verdana, Geneva, sans-serif padding:3px font-size:12px }

h3{ clear:both}

li{ padding:2px 0 list-style:none}

</style>

<script type="text/javascript">

function get_cookie(cookieName){

    //判断cookie是否存在

    if (document.cookie.length>0){

        pos=document.cookie.indexOf(cookieName + "=")

        if (pos!=-1){ 

            pos=pos + cookieName.length+1 

            last=document.cookie.indexOf("",pos)

            if (last==-1) last=document.cookie.length

            return unescape(document.cookie.substring(pos,last))

        } 

    }

    return "cookie不存在!"

}

</script>

</head>

<body>

<input type="button" value="获取cookie" onclick="alert(get_cookie('cname'))"/>

</body>

</html>