简体   繁体   English

在php中创建了一个cookie,现在尝试在javascript中更新它?

[英]made a cookie in php, now trying to update it in javascript?

echo  "<script type=\"text/javascript\">";
echo "function del_cookie()";
echo "{";
echo "document.cookie = logged_amount + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';";
echo "}";

echo "</script>";

echo "<form action=logout.php name=Logout>";
echo "<input type=submit name=submit value=\"Log Out\"> | <a href='./archive.php'>View History</a> | <a href='#' onclick='del_cookie'>Mark as read</a><form>";


setcookie("logged_amount", $x, time() + 60 * 60 * 24 * 30);

When I try to click "Mark as read" it doesn't really work. 当我尝试单击“标记为已读”时,它确实不起作用。 Am I missing something? 我错过了什么吗? Also if I can I'd really like to update the cookie with the $x value. 另外,如果我可以,我真的想用$x值更新cookie。

document.cookie =  logged_amount +
                  ^             ^

You didn't surround the logged_amount with quotes, so Javascript's seeing it as an (undefined) variable. 您没有用引号包围logged_amount ,因此Javascript将其视为(未定义的)变量。 So you're trying to set a cookie with a blank name. 所以你试图设置一个空白名称的cookie。 Try 尝试

document.cookie = 'logged_amount' + ...

instead. 代替。

Note: setcookie() in PHP doesn't work after the headers are sent. 注意:发送标头后,PHP中的setcookie()不起作用。 In other words, you need to place setcookie() before you echo out anything. 换句话说,你需要在echo任何东西之前放置setcookie()

you can use the jquery plugin: https://github.com/carhartl/jquery-cookie 你可以使用jquery插件: https//github.com/carhartl/jquery-cookie

to read cookies in jquery use the: 在jquery中读取cookie使用:

$.cookie('cookie_name')

and to set it use: 并设置它使用:

$.cookie('cookie_name','cookie_val')

I gave up with javascript. 我放弃了javascript。

if (isset($_GET['markread'])) {
    if ($_GET['markread'] == 1) {
        setcookie("logged_amount", $x, time() + 60 * 60 * 24 * 30);
        echo "<meta http-equiv='refresh' content='0;url=view.php'>";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM