我正忙于学习 Ajax,需要将 Postgres 用于支持的数据库。我找到了一个适用于 Mysql 的示例,但是当我将其转换为 Postgres 时,它停止工作。从 Mysql 切换到 Postgres 时,我没有对 HTML 代码进行任何更改。
当我在命令行 (php test.php) 执行 php 代码时,它会工作并输出正确的行数和数据。
这是php
<?php
$dbh = pg_connect("host=192.168.0.8 dbname=test user=test password=test");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "SELECT * FROM users";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
// iterate over result set
// print each row
while ($row = pg_fetch_array($result)) {
echo "Name: " . $row[1];
echo "<BR />";
}
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
?>
这是html
<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "test.php";
var fn = document.getElementById("name").value;
var vars = "name="+fn;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
document.getElementById("name").value = "";
}
</script>
<script type="text/javascript">
function setFocus()
{
document.getElementById("name").focus();
}
</script>
</head>
<body onload="setFocus()">
<div>
<form name="input" action="" onsubmit="ajax_post(); return false;">
Barcode : <input type="text" id="name" size="30"><br />
</form>
</div>
<div style="background-color: lightyellow; border: 1px solid black; width: 400; height: 300;">
<div id="status"></div>
</div>
</body>
我注意到的一件事是,当我在命令行中使用 postgres 运行 test.php 文件时,总是将换行符附加到数据的末尾。
谢谢哦