【发布时间】:2018-09-17 22:35:47
【问题描述】:
我的任务目标是使用 ajax 和 php 每 5 秒从 postgresql 数据库填充数据。我遵循了示例How to put data from database table to a html table using ajax and php。我是 PhP 的新手,所以我不知道为什么没有填充数据。我对代码进行了测试,并成功在控制台中获取了数据,但在表格中没有。 客户端代码
<!DOCTYPE html>
<html>
<head>
<style> <?php include './../css/hardwarestatus.css'; ?> </style>
</head>
<body>
<div class="maindiv">
<div id="tagsDiv">
<h3>Estat Tags</h3>
<?php
echo '<table id="tags_table">';
echo "<tr>";
echo '<th>' . "TAG" . '</th>';
echo '<th>' . "BATTERY" . '</th>';
echo '<th>' . " Time " . '</th>';
echo '<th>' . "Status" . '</th>';
echo "</tr>";
echo '</table>';
?>
</div>
</div>
<script src='http://code.jquery.com/jquery-3.1.1.min.js'></script>
<script>
$(document).ready(function(){
UpdateHTMLTable();
setInterval(function() {
UpdateHTMLTable();
}, 5000); // 5000 millisecond(5 second)
function UpdateHTMLTable(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
for (i = 0; i < myObj.length; i++) {
console.log(myObj[i]);
var row = $("<tr />");
$("<td />").text(myObj[i].mac).appendTo(row);
$("<td />").text(myObj[i].battery).appendTo(row);
$("<td />").text(myObj[i].ts).appendTo(row);
$("<td />").text(myObj[i].ts).appendTo(row);
row.appendTo('#tags_table');
}
}
};
xmlhttp.open("GET", "pages/estat_hardware_server.php", true);
xmlhttp.send();
}
});
</script>
</body>
</html>
在服务器端,我的代码是
<?php
header("Content-Type: application/json; charset=UTF-8");
$host = ip of the host";
$port ="port no.";
$user = "user";
$pass = "123";
$db = "db_name";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query = "Query string";
$result = pg_query($con, $query) or die("Cannot execute query: $query\n");
if(pg_num_rows($result))
{
$data=array();
while($row=pg_fetch_array($result))
{
$data[] = array(
'mac'=>$row['mac'],
'ts' =>$row['ts'],
'battery'=>$row['battery']
);
}
echo json_encode($data);
pg_free_result($result);
pg_close($con);
}
?>
【问题讨论】:
-
有很多可能出错的地方,所以我们需要更多信息,说明你能走多远,是否有任何错误消息等。 - 你d 需要先做一些调试。
-
如果您在浏览器中手动打开
pages/estat_hardware_server.php,您是否获得了预期的数据? -
是的,我正在从客户端的服务器获取所有数据。正如我在客户端所做的那样:console.log(myObj[i]);并且结果成功来自服务器。
-
#mytags_table实际上叫tags_table,所以row.appendTo('#mytags_table');这一行应该是row.appendTo('#tags_table'); -
首先您应该打开:pages/estat_hardware_server.php 并检查您是否在此处看到错误并与我们分享。如果没有错误,您应该检查浏览器控制台
标签: php ajax postgresql