dongzi1397 2014-11-12 13:50
浏览 48

如何通过PHP将DB上的值传递给JAVASCRIPT

<?php
    // Connect to database server
    mysql_connect("192.168.1.101/phpmyadmin/", "root", "praticas") or die (mysql_error ());

    // Select database
    mysql_select_db("logs_history") or die(mysql_error());

    //---> at this point, I want yo pull a VALUE from a column called potencia_ativa and insert in 
    // the code JS below


      mysql_query($strSQL);
    // Close the database connection
    mysql_close();
    ?>

//JS code-------------------------------------------------------------------------------------------

<div id="graphHolder" style="height:75%;width:100%"></div>
<script type="text/javascript">

setInterval(
            function() {

                var d1 = [];
                for (var i = 0; i < parseInt(document.getElementById('number').value,10); i += 0.5) {
                    d1.push([  //----------> pull the value from the php/DB as a FLOAT
                        ]);
                }

                $.plot("#graphHolder", [{
                        label: "Label",
            data: d1,
                        lines: { show: true, fill: true }
                }
                ]);
            }, 1000);
</script>
  • 写回答

2条回答 默认 最新

  • dro80463 2014-11-12 14:07
    关注

    Remember, PHP executes on the server and GENERATES the page that runs the Javascript on the client. Putting a value from PHP into the JS code is as simple as:

    <script>
       var foo = <?php echo json_encode('bar'); ?>;
    </script>
    

    If you need to send the PHP data over AFTER the page was generated and already send to the client, then you need to have the client execute an AJAX request to fetch that data from the server. Once PHP has shoved the page out the door, it's basically done and can't "reach out" to the client to do updates on its own.

    Also: Note the use of json_encode(). You should NEVER dump output from PHP directly into a Javascript context without it. Anything else puts you at risk of generating JS syntax errors, which will kill the entire JS code block.

    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)