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 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大