【问题标题】:Pass an array from php to javascript将数组从 php 传递到 javascript
【发布时间】:2015-04-10 16:54:16
【问题描述】:

我正在尝试将一个数组从 php(在单独的文件中)端传递给 JavaScript 并更新 HTML 表。 php端的数组是MySQL查询的结果。 这是我到目前为止所做的:

function updateSensorsTable() {
    $.getJSON("/getTableFromDB.php", function (json) {
     for (i = 0; i < 8;i++ )
         document.getElementById(i).innerHTML = json[i];
    });
}
<?php

include("connect_to_mysql.php");

$result = mysql_query("SELECT value FROM sens" );

while ($row = mysql_fetch_row($result)) {
    $php_array[]=$row[0];
}

echo json_encode($php_array);

?>

【问题讨论】:

  • 从 0 到 7 的 for 循环看起来有点可疑(改用 json.length?)。但是从看起来你的 PHP 数据被发送到 JS 的情况来看,就好了。您的问题是关于如何在 JavaScript 中构建表格?
  • “我几乎不知道 php 或 java - JavaScript and Java are different。我知道您可能正在将 JavaScript 缩短为 Java,而我可能很迂腐。 (您已标记 javascript 并在您的问题中引用 Java)
  • 请注意,mysql_* 函数不应再使用,如the extension is deprecated
  • 直接从浏览器访问php页面/getTableFromDB.php,看看它是否输出了应该输出的内容。这样你就可以判断你的 php 脚本或 javascript 是否有错误。
  • @tier1 doesn't matterwhile 循环没有范围问题。我们现在正处于切线状态。请回到OP的问题。

标签: javascript php mysql sql


【解决方案1】:

别忘了设置标题:

header('Content-Type: application/json');

当您执行“document.getElementById(i)”时,您会尝试访问具有错误 ID(整数)的元素...这是规则:

ID 和 NAME 标记必须以字母 ([A-Za-z]) 开头,后跟任意数量的字母、数字 ([0-9])、连字符 ("-")、下划线 (" _")、冒号 (":") 和句点 (".")。

【讨论】:

  • 我添加了 'header('Content-Type: application/json');'在echo 命令正上方的php 文件中,也更改了id - 仍然不行
  • 显示你的表格的 HTML
【解决方案2】:

这是完整的页面

<script type="text/javascript"  >

     setInterval(updateSensorsTable, 2000);
     setInterval(updatePower, 1000);


     function showValue(value) {
         //show value in html
         document.getElementById("brightnesValue").innerHTML = value;
         //Set brightness value to DB id=10
         callPage('/setValueToDB.php?value=' + value + '& id=10' + '', document.getElementById(''));
     }

     function TurnLedOn() {
         //TODO: need to set the led state and update the sql server
         document.getElementById("ledStatus").src = "/LedOn.png";
         callPage('/setValueToDB.php?value=1&id=9' + '', document.getElementById(''));
     }

     function TurnLedOff() {
         //TODO: need to set the led state and update the sql server
         document.getElementById("ledStatus").src = "/LedOff.png";
         callPage('/setValueToDB.php?value=0&id=9' + '', document.getElementById(''));
     }

     function AjaxCaller() {
         var xmlhttp = false;
         try {
             xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
             try {
                 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
             } catch (E) {
                 xmlhttp = false;
             }
         }

         if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
             xmlhttp = new XMLHttpRequest();
         }
         return xmlhttp;
     }

     function callPage(url, div) {
         var ajax = AjaxCaller();
         ajax.open("GET", url, true);
         ajax.onreadystatechange = function () {
             if (ajax.readyState == 4) {
                 if (ajax.status == 200) {
                     div.innerHTML = ajax.responseText;
                 }
             }
         }
         ajax.send(null);
     }

      function updateSensorsTable() {
         
         for (i = 0; i < 8; i++) {
             callPage('/getVarFromDB.php?offset=' + i , document.getElementById(i));
         }
         /*
         $.getJSON("/getTableFromDB.php", function (json) {
             for (i = 0; i < 8;i++ )
             document.getElementById(i).innerHTML = json[i];
             });
             */
             }

     function updatePower() {
         callPage('/getVarFromDB.php?offset=' + 10, document.getElementById('powerValue'));
     }

 </script>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0"/>
        <title>SmartLight</title>
    </head>

    <body bgcolor="#E6E6FA">
        <br></br>
        <table class="sensorsTable" align="center">
            <thead>
            <tr >
                <th>Sensor</th>
                <th>Value</th>
            </tr>
            </thead>
            <tbody>
                <tr>
                    <td align="left">GPS</td>
                    <td align="center" id="0">0</td>
                </tr>
                <tr>
                    <td align="left">Temperature</td>
                    <td align="center" id="1">0</td>
                </tr>
                <tr>
                    <td align="left">Pressure</td>
                    <td align="center" id="2">0</td>
                </tr>
                <tr>
                    <td align="left">Light</td>
                    <td align="center" id="3">0</td>
                </tr>
                <tr>
                    <td align="left">Altitude</td>
                    <td align="center" id="4">0</td>
                </tr>
                <tr>
                    <td align="left">Accelerometer</td>
                    <td align="center" id="5">0</td>
                </tr>
                <tr>
                    <td align="left">Humidity</td>
                    <td align="center" id="6">0</td>
                </tr>
                <tr>
                    <td align="left">Camera</td>
                    <td align="center" id="7">0</td>
                </tr>
            </tbody>
        </table>

        <br></br>

         <table class="ledTable" align="center">
                     <tr>
                         <td align="center"><input type="image" src="/TurnOn.png"  id="turnOn" width="60" height="60" onclick='TurnLedOn()'></td>
                         <td align="center"><input type="image" src="/TurnOff.png" id="turnOff" width="60" height="60" onclick='TurnLedOff()'></td>
                         <td align="center"><img src="/LedOn.png" style="width:60px;height:60px" id="ledStatus"></td>
                     </tr>
                     <tr>
                                 <td align="center" id="ledOnButton">LED On</td>
                                 <td align="center" id="ledOffButton">LED Off</td>
                                 <td align="center">LED Status</td>
                     </tr>
         </table>

        <div align="center">
            Brightness:
            <input type="range" id="brightnesBar" min="0" max="100" value="0" step="1" onchange="showValue(this.value)" />
            <span id="brightnesValue">0</span>
            <table align="center" class="power">
                <tr>
                    <td align="center" id="powerValue">0</td>
                    <td align="left">mW</td>
                </tr>
            </table>
        <div align="center" >LED Power Meter</div>
        </div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    相关资源
    最近更新 更多