简体   繁体   English

如何使用 cookie 将 javascript 变量传递给 php 变量

[英]How to pass javascript variable to php variable by using a cookie

when I'm trying to run this code to forward javascript value (cookie_user) to PHP value (username).当我尝试运行此代码以将 javascript 值(cookie_user)转发到 PHP 值(用户名)时。

here is my code:这是我的代码:

 <script> // Creating a cookie after the document is ready $(document).ready(function () { var cookies = document.cookie.split(";") var cookiePair = cookies[0].split("="); var cookie_user=cookiePair[1]); createCookie("username", cookie_user, "10"); }); // Function to create the cookie function createCookie(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } else { expires = ""; } document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/"; } </script> <?php $username= $_COOKIE["username"]; ?>

when I execute the code, I get this error: "Undefined index: username" the PHP part is not working.当我执行代码时,我收到此错误:“未定义索引:用户名”PHP 部分不起作用。 what should I do to make it right?我应该怎么做才能使它正确?

Thanks谢谢

You have an issue in your existing JS code with extra parenthesis on line 5 , Also you can't access cookie instantly from PHP after setting it on javascript .您现有的 JS 代码中存在问题,第5行带有额外的括号,而且在 javascript 上设置后,您也无法立即从 PHP 访问 cookie

So you've to modify on your PHP part also, initially check cookie exists or not with isset() ?因此,您还必须修改 PHP 部分,最初使用isset()检查 cookie 是否存在? when you reload your page it will set the username cookie that will be accessible on your $_COOKIE['username'] later.当您重新加载页面时,它会设置稍后可在$_COOKIE['username']上访问的用户名 cookie。

ON JS ,在 JS上,

$(document).ready(function () { 

    var cookies = document.cookie.split(";")
    var cookiePair = cookies[0].split("=");
    var cookie_user=cookiePair[1]; // remove ending parenthesis here  
    createCookie("username", cookie_user, "10"); 
}); 

// Function to create the cookie 
function createCookie(name, value, days) { 
    var expires; 

    if (days) { 
        var date = new Date(); 
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); 
        expires = "; expires=" + date.toGMTString(); 
    } 

    else { 
        expires = ""; 
    } 

    document.cookie = escape(name) + "=" +  
    escape(value) + expires + "; path=/"; 
} 

ON PHP ,在 PHP 上

<?php
$username = isset($_COOKIE['username'])? $_COOKIE['username']:'cookie not set';
echo $username;
?>

Alternatively, you can use ajax to send data from your client-side js to server-side PHP或者,您可以使用ajax将数据从客户端 js 发送到服务器端 PHP

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

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