如何在PHP中获取JavaScript变量值

2022-08-30 13:54:41

我想要JavaScript变量的值,我可以使用PHP访问它。我正在使用下面的代码,但它在PHP中不返回该变量的值。

// set global variable in javascript
    profile_viewer_uid = 1;

// php code

$profile_viewer_uid=$_POST['profile_viewer_uid']; 

这给了我以下错误:-

A PHP Error was encountered
Severity: Notice
Message: Undefined index: profile_viewer_uid

我使用的另一个php代码,它给出了空值

$profile_viewer_uid = "<script language=javascript>document.write(profile_viewer_uid);</script>

当我回声时,它什么也没显示出来。


答案 1

您需要使用 JS 将 URL 发送回去,其中包含一个变量,例如:http://www.site.com/index.php?uid=1

通过在JS中使用类似这样的东西:

window.location.href=”index.php?uid=1";

然后在 PHP 代码中使用 $_GET:

$somevar = $_GET["uid"]; //puts the uid varialbe into $somevar

答案 2

添加一个包含您要访问的 javascript 变量的 Cookie。

document.cookie="profile_viewer_uid=1";

然后通过 php 访问它

$profile_viewer_uid = $_COOKIE['profile_viewer_uid'];