如何在PHP中访问JavaScript变量?
我在我的如何在PHP中访问JavaScript变量?,javascript,php,html,reactjs,variables,Javascript,Php,Html,Reactjs,Variables,我在我的encode.html文件中有这个工作的JS代码: <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <script type="text/javascript">
encode.html
文件中有这个工作的JS代码:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script type="text/javascript">
var value; //this is the Value variable I want to access in PHP.
value = 'some value here'; //value variable gets updated.
</script>
</body>
</html>
<?php
$jsValue = 'value variable from javascript should go here';
//I want to access the value variable (from javascript) in the above PHP variable.
echo $jsValue; //print the value
?>
我想把两个文件合并成一个。并从JavaScript中访问变量值
,并在PHP中回显它,然后在以后的一些函数中使用它。因此,有两件事:
- 我应该如何正确格式化代码(这样我就可以在一个文件中看到所有代码)
- 在合并PHP&JS代码之后,我应该如何从PHP中的JS访问
变量,以便将其分配给本地PHP变量并在以后使用它值
我希望你能理解我的问题。任何帮助都将不胜感激 我的建议是将值保存到cookie中。如果这样做,可以将值拉入PHP或Javascript Javascript代码
<script type="text/javascript">
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
setCookie("shared_value", "some value here", 1);
</script>
函数setCookie(名称、值、天数){
var=”;
如果(天){
变量日期=新日期();
date.setTime(date.getTime()+(天*24*60*60*1000));
expires=“;expires=“+date.toutString();
}
document.cookie=name+“=”+(值| |“”)+expires+“path=/”;
}
setCookie(“共享值”、“此处的某些值”,1);
PHP代码
<?php
/** check to see if shared_value cookie is found, then display */
echo (isset($_COOKIE['shared_value']) ? $_COOKIE['shared_value'] : 'value not set';
?>
你的PHP代码和JavaScript代码被互联网隔开。这意味着什么?这是否回答了你的问题?一般来说,这意味着您需要将js变量的值发送到服务器(php代码),然后在那里捕获并使用它。@Jeto那么,有没有办法将变量从客户端传递到服务器端?