dongzhi2014 2013-05-25 14:15
浏览 14

javascript在另一个文件中使用php [关闭]

i want to tidy up my index.php. i have some scripts which i want to move to another files.

atm i come to this, i hava javascript which has php in it to echo values from database. i came to solution, copy that to another php file, like script.php, and just include it with php.

<!-- AUTO complete -->
<script src="/pages/JQuery/js/jquery-1.8.3.js"></script>
<script src="/pages/JQuery/js/jquery-ui-1.9.2.custom.js"></script>
<link rel="stylesheet" type="text/css" href="/pages/JQuery/css/no-theme/jquery-ui-1.10.3.custom.css" />
<?php include './pages/skripti/autocomplete.php'; //pats skripts ?> 

and

<script>
    jQuery(function($) {
        var availableTags = [
        <?php 
            $names = $db->query("SELECT * FROM names");
            while ($name = $names->fetch_object()) {
                echo '"' . $name->rs_name . '",';
            }
        ?>
        ];

        $( "#autocomplete" ).autocomplete({
            source: availableTags
        });
    });
</script>

The question is: How good solution it is?

  • 写回答

1条回答 默认 最新

  • douhe8981 2013-05-25 16:00
    关注

    Personally, I feel that combining JavaScript that should be cached on the client and PHP is bad practice. In the future, it'll be much more difficult to maintain, is slower for the client as it'll have to be downloaded every page load, and results in more http requests (or a larger single http request).

    <?php
    $names = $db->query("SELECT rs_name FROM names");
    $list = array();
    while($name = $names->fetch_object()) {
      $list[] = $name->rs_name;
    }
    ?>
    <script type="text/javascript" src="js/mscript.js"></script>
    <script>
    // Now, let's initialize our functions on jQuery load
    jQuery(function($) {
      auto_complete(<?php echo json_encode($list); ?>);
    });
    </script>
    

    Then, mscript.js will contain:

    var auto_complete = (function(auto_list) {
      $( "#autocomplete" ).autocomplete({
         source: auto_list
      });
    });
    

    Add additional functions or classes in mscript.js. Then the client only has to download that once and not every page load.

    In this example it doesn't seem applicable, but when you add different JS functionality in the future, it'll make the code much more portable and easy to work with.

    Edit: As a side note, I believe that some versions of IE have issues with trailing , in arrays. json_encode can take care of that for you and also will escape the values for you (in case you have an rs_name with a ", for example.

    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP