dsag14654 2014-02-21 09:58
浏览 53

将服务器端变量传递给PHP中的Javascript [重复]

This question already has an answer here:

What is the best way to pass a server-side PHP variable to Javascript?

To simplify the problem assume that we have a variable in PHP ($phpVar) and we want to assign its value to a Javascript variable (jsVar)

Javascript files are loaded in html - they are not created dynamic!

Some food for thought:

1. Print with PHP before loading Javascript files:

    <script language="javascript" type="text/javascript">
       var jsVar= <?php echo $phpVar?>;
    </script>

2. Store in DOM (in hidden elements)

a. in PHP:

    <span data-name="phpVar" data-value="<?php echo $phpVar?>"></span>

b. Read in Javascript files (assuming jQuery available):

    var jsVar= $('span[data-name="phpVar"]').attr('data-value');

3. Ask it with AJAX after page has loaded

Obviosly not the best solution. Doesn't fit to all scenarios and requires an additional request...

In conclusion:

  • They both seem ugly to me... Is there a better approach?
  • Is there any frameworks that can handle this dependecies? Please keep server reconfiguration minimal.
</div>
  • 写回答

2条回答 默认 最新

  • dongli1887 2014-02-21 10:03
    关注

    It depends on the situation, but in common, predominantly to use first case. But don't forget about quotes if you pass a string:

    <script language="javascript" type="text/javascript">
        var jsVar = '<?php echo $phpVar?>';
    </script>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数