doujiao3072 2010-10-30 00:59
浏览 54
已采纳

从服务器加载JS配置?

I want my JS to load certain information that needs to come from the server. Examples would be URLs, language specific messages, etc. What is the best way to get this information from the server to the JS?

Right now, I have such values stored in an actual JS file. I don't like this approach because information is duplicated on the server side.

Would it be a good idea to have an initial JS to make an Ajax request to get all these details? Perhaps store this in a global variable so that it is accessible from anywhere? (A benefit of my current approach is that I don't need to necessarily set such information as a global variable; I could, for example, hard code and alert message where it is needed).

Any advice on best practice for my situation?

  • 写回答

4条回答 默认 最新

  • duan5362 2010-10-30 01:02
    关注

    As you already use PHP, why not use that to generate a dynamic .js file that contains all your variables and include that on the page?

    PHP:

    var foo = '<?php echo $foo; ?>';
    var bar = '<?php echo $bar; ?>';
    

    HTML:

    <script type="text/javascript" src="vars.php"></script>
    <script type="text/javascript" src="actual_javascript_stuff.js"></script>
    ...
    

    This way you can keep all your config in one place. You can include the PHP's config file and populate the JavaScript variables using that.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配