我有PHP代码,在其中我作为postgres数据库表字段得到了回显,我想在基于html和JavaScript的Web应用程序中显示这些字段。现在我可以将它们加载到网页中,但必须将网页重新加载到获取新更新的值。我想在不重新加载应用程序的情况下自动在文本框中获取它们。我读到ajax请求会有所帮助 给出的是我正在与html一起使用以显示案例记录的php代码,但我每次都必须重新加载页面以使其更新
<?php
$host = "host = localhost";
$port = "port = 5432";
$dbname = "dbname = geoserver";
$credentials = "user = postgres password=password";
$db = pg_connect( "$host $port $dbname $credentials" );
$sql =<<<EOF
SELECT * from audit.logged_actions
ORDER BY action_tstamp_tx DESC
LIMIT 5;
EOF;
$ret = pg_query($db, $sql);
if(!$ret) {
echo pg_last_error($db);
exit;
}
while($row = pg_fetch_row($ret)) {
// echo "e = ". $row[1] . "\n";
echo "<input type='text' value='$row[14] '/>";
echo "<input type='text' value='$row[13] '/>";
}
echo "Operation done successfully\n";
pg_close($db);
?>
答案 0 :(得分:0)
问题是,在浏览器呈现php脚本的输出后,它不再与php连接。 HTTP就是这样工作的。
要在不刷新整个页面的情况下显示输出,您需要使用javascript向PHP脚本发出另一个HTTP请求。
类似这样的东西:
<?php
$host = "host = localhost";
$port = "port = 5432";
$dbname = "dbname = geoserver";
$credentials = "user = postgres password=password";
$db = pg_connect( "$host $port $dbname $credentials" );
$sql =<<<EOF
SELECT * from audit.logged_actions
ORDER BY action_tstamp_tx DESC
LIMIT 5;
EOF;
$ret = pg_query($db, $sql);
if(!$ret) {
echo pg_last_error($db);
exit;
}
?>
<div id='content'>
<?php while($row = pg_fetch_row($ret)) { ?>
<input type='text' value='<?= $row[14] ?>'/>
<input type='text' value='<?= $row[13] ?>'/>
<?php } ?>
Operation done successfully
<script>
(function() {
const secondsToRefresh = 5;
const Http = new XMLHttpRequest();
const url='#YOUR_PHP_SCRIPT_URL#';
setTimeout(function() {
Http.open("GET", url);
Http.send();
}, secondsToRefresh * 1000);
Http.onreadystatechange=(e)=>{
document.getElementById('data').innerHTML = Http.responseText;
}
})()
</script>
</div>";