在PHP和JavaScript之间交换变量 [英] Exchanging variables between PHP and JavaScript

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

问题描述

所选单选按钮将通过下拉框显示其对应的城市列表。
例如,在选中的单选按钮安大略省时,将显示一个带有匹配城市的下拉框(在此示例中,区域为安大略省,ID为77)。

The selected radio button will show its corresponding list of cities by a dropdown box. For example, upon the selected radio button ‘Ontario’, a dropdown box with matching cities will show up (in this example the ‘Region’ is Ontario and the id is 77).

示例中下面提到的所有PHP函数,循环和JavaScript代码都正常工作:

All PHP functions, loops and the JavaScript code mentioned below in the example, are working correctly:

<script type="text/javascript">
$(document).ready(function(){
  $('#locationTree input:radio').change(function() {
    var buttonPressed = $('input:radio[name=Region]:checked').val();

    if(buttonPressed == 77) {
      var listCities = $("select[name='City']");
      <?php View::newInstance()->_exportVariableToView(77); ?>
      <?php while(has_list_cities()) { ?>
        $("<option><?php echo list_city_name(); ?></option>").appendTo(listCities);
      <?php } ?>                
    } 

  });   
});
</script>  

要获取不同地区的城市列表,而不是具体到77,我可以略微更改PHP代码如下:

To get list of cities by different regions and not specifically to 77, I can slightly change the PHP code as follows:

 <?php View::newInstance()->_exportVariableToView($regionCode); ?>

由于变量'buttonPressed'检测到'Region'的选定ID,我可以添加以下内容简单脚本:

and since the variable ‘buttonPressed’ detects the selected id of ‘Region’, I can add the following simple script:

<?php $regionCode = "<script>document.write(buttonPressed)</script>"; ?>   

经过上述变更后:

var listCities = $("select[name='City']");
<?php $regionCode = "<script>document.write(buttonPressed)</script>"; ?>   
<?php View::newInstance()->_exportVariableToView($regionCode); ?>

我知道PHP是运行服务器端而JavaScript是运行客户端但我认为我的简单解决方案在PHP和JavaScript之间交换变量应该有效...但它不起作用。我真的要求有人帮助我让它工作。

I know PHP is run server side and JavaScript is run client side but I thought that my simple solution for exchanging variables between PHP and JavaScript should work… but it doesn’t work. I really ask someone help me get it working.

推荐答案

使用数据属性属性交换变量(服务器切换到客户端)HTML 5提供。我这样做是为了初始页面加载。

Exchange variables (sever to client) by using the data attribute properties HTML 5 provides. I do this for initial page loads.

要在初始页面加载后交换变量,可以使用ajax调用。

To exchange variables after the initial page load, one may use ajax calls.

数据属性示例

HTML通过PHP写

<div id='universals' data-path='/zz/' data-load='1'></div>

JavaScript

var data_dom = $('#universals')[0],
    key,
    universals = [];
for (key in data_dom.dataset) {
    universals[key] = data_dom.dataset[key];
}

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

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