javascript函数保存到cookie

时间:2010-01-26 04:04:21

标签: php javascript

现在,我有一个函数macs,我需要实现这个函数来保存在一个cookie中并将它存储在mysql中..

那我该如何将这个功能放在一起呢?

        <script language="JavaScript">

        function getMacAddress(){
          document.macaddressapplet.setSep( "-" );
          return (document.macaddressapplet.getMacAddress());
        }

        function setCookie(c_name,value,expiredays)
        {
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
        }

        setCookie('cookie_name','getMacAddress()','1');
        </script> 
        <body>

        <?php
         //Defaults to 1
        $javascript_cookie = isset($_COOKIE["cookie_name"]) ? $_COOKIE["cookie_name"] : 1;
        echo "$javascript_cookie";

        // db insert query
        $dbhost = 'localhost';
        $dbuser = 'root';
        $dbname = 'registration';
        mysql_connect($dbhost, $dbuser) or die("Could not connect database");
        mysql_select_db($dbname);
        $sql_query = mysql_query("SELECT * from user WHERE UserID ='".$_POST['newUserID']."'");
        $sql = "INSERT INTO test(mac) VALUES ('".$javascript_cookie."')";
        mysql_query($sql);
        ?>

3 个答案:

答案 0 :(得分:2)

以下是我用来处理cookie的两个函数:

function writeCookie(name,value,days) {
    var date, expires;
    if (days) {
        date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();}
    else{
        expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var i, c, ca, nameEQ = name + "=";
    ca = document.cookie.split(';');
    for(i=0;i < ca.length;i++) {
        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 '';
}
  • 名称是您要存储的信息的名称
  • 其值
  • 是设置和到期日期,如果为空

答案 1 :(得分:0)

使用DojoJQuery等Javascript库。它们具有良好的简化界面以实现这样的常见功能,并隐藏了API背后的大多数混乱的跨浏览器兼容性问题。

答案 2 :(得分:0)

好吧,对于JavaScript / setCookie部分,如果用getMacAddress()替换'Text3123234',那应该可以帮到你。所以该行应如下所示:

setCookie('cookie_name', getMacAddress(), 1);