从PHP设置JavaScript变量 [英] Set JavaScript variable from PHP

查看:103
本文介绍了从PHP设置JavaScript变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从PHP设置JavaScript变量strUser?

How I can set the JavaScript variable strUser from PHP?

我使用以下代码:

<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>";
?>


推荐答案

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

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

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

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

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

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

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.

这篇关于从PHP设置JavaScript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆