从 PHP 设置 JavaScript 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18189198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:07:37  来源:igfitidea点击:

Set JavaScript variable from PHP

phpjavascript

提问by user2627035

How I can set the JavaScript variable strUser from PHP?

如何从 PHP 设置 JavaScript 变量 strUser?

I am using the following code:

我正在使用以下代码:

<script>
function val()
{
    var e = document.getElementById("ali");
    var strUser = e.options[e.selectedIndex].text;

}
</script>
brand<select id="ali" onChange="val()">
<?php
   $brand=modsearchkhodroHelper::retrieve();
   foreach($brand as $item)
   {   
   ?>
       <option value="<?php echo $item['brand']?>" selected="<?php  $id=$item['brand']?>">
           <?php echo $item['brand']?>
       </option>
   <?php
   }
   echo "</select>";
?>

回答by Joshua Dwire

If you want to set the variable when the page loads, you could use something like this in the PHP code:

如果你想在页面加载时设置变量,你可以在 PHP 代码中使用这样的东西:

<script type="text/javascript">var strUser = <?php echo json_encode($someVariable); ?>;</script>

Just make sure to remove the later variable declaration from the JavaScript.

只需确保从 JavaScript 中删除后面的变量声明即可。

If you want to set the variable after the page loads, you'll have to use an AJAX call to ge the value from the server.

如果要在页面加载后设置变量,则必须使用 AJAX 调用从服务器获取值。

回答by Nathan Srivi

Use Cookie in your javascript

在 JavaScript 中使用 Cookie

<script type="text/javascript">
    document.cookie = "cookieName=cookieValue";
</script>

in your php

在你的 php

<?php 
   $phpVar =  $_COOKIE['cookieName'];

   echo $phpVar;
?>