douzhushen_9776 2017-02-17 16:58
浏览 59
已采纳

如何正确创建JavaScript变量并从PHP调用函数

to be clear, I'm not asking how to create a JS variable or function from PHP, rather I'm asking about the correct way or best practice to do so.

I have some PHP variables I need to use in JavaScript to make some modifications later, I also need to run a JS function when these variables are initialized.

The most obvious way to do this is to add a <script> tag and enter my JS info in there, as follows:

    ?>
    <script>
        $(document).ready(function () {
            var my_js_string = <?php my_php_string ?>
            my_js_function();
        });
    </script>
    <?php

That way I have a global JS var and the function runs on document.ready.

However, this feels wrong. If I need to create multiple JS variables from PHP the code would be bloated with scripts and document.ready(s) everywhere. Even when the document.ready is not necessary, initializing many JS global variables using this method makes the code so much harder to read and debug. Having JS globals is bad practice as well. Plus what if it's sensitive information? You don't want it floating around as a global that can be accessed by anyone.

Any recommendations on a better methodology?

One option I was thinking on, was the creation of events, fill up events with the information and then retrieve it on the proper .js file, creating local variables, but this could cause the same issue, many unnecessary events floating around.

Another way I thought was to create HTML elements containing the data, either in plain text, as data- attributes or any other method. This is a good practice in some cases, but I don't think it's the best way when you have many variables or the variables contain sensitive information you don't want to show in the DOM.

If this is a duplicate answer, or you can direct me to relevant articles that address this, I would appreciate it, as I didn't know how to correctly search for this and couldn't find good resources.

  • 写回答

1条回答 默认 最新

  • douke1954 2017-02-17 17:12
    关注

    Personally I don't like generating JavaScript from PHP so I usually either add the data to values of hidden inputs if it's just a small amount, or otherwise load the data in separately using AJAX and JSON, which just seems cleaner to me, although it does require a separate HTTP request.

    Here's a brief example of how to do this using AJAX and JSON with JQuery:

    In the .js file for your page add:

    // When the document is ready
    $(function(){
        $.post('get_json.php', function(response){
            console.log(response.data)
        }, 'json')    
    })
    

    In your get_json.php file:

    <?php
       // Create an array with the data you want to send back
        $response = array(
            'data' => 'test'
        );
        echo json_encode($response);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R