如果我正确理解了这个问题,那么当我试图弄清楚 PostgreSQL 时,我自己实际上已经完成了一个非常相似的项目。这就是我所做的:
首先,我创建了一个输入(注意以下代码行中的 oninput="zipChanged()"):
<input list="zips" name="zips" id="zipCode" oninput="zipChanged()" placeholder="ZIP code">
然后我给了它一个列表,其中显示了 5 个可能的选项,使用 <datalist> 标记作为放置所有选项的块,并使用 <option> 标记放置每个可能的选项。
<datalist id="zips">
<option id="zipOption1">
<option id="zipOption2">
<option id="zipOption3">
<option id="zipOption4">
<option id="zipOption5">
</datalist>
在此之后,由于我在输入中写入了 oninput="zipChanged",每次用户在写入邮政编码时写入或删除任何数字时,都会激活函数 zipChanged()。函数是这样的:
var currentSearch = document.getElementById("zipCode").value;
var url = "http://127.0.0.1:8096/?need=" + currentSearch;
xhttp.open("GET", url, true);
xhttp.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
zipPossibilities_G = JSON.parse(this.responseText);
fillZipPossibilities();
} else { }
}
};
xhttp.send();
让我为您分解功能:
以下行用于将用户在文本输入中写入的值放入名为 currentSearch 的变量中。
var currentSearch = document.getElementById("zipCode").value;
其余代码用于让我的 HTML 文件连接到我用来连接到我的 PostgreSQL 数据库的 nodeJS 服务器,我从中提取了数据库中与用户的邮政编码部分最相似的邮政编码已输入作为向用户显示他们可能尝试输入的可能的邮政编码的一种方式。
服务器能够通过查找以与用户输入的邮政编码部分相同的数字开头的邮政编码来做到这一点。它向数据库发送了一个 SQL 代码,告诉它提供信息,代码如下:
select "[name of the column in which the Zip Codes are]" from "[name of your table in the databse]" where "[name of the column in which the Zip Codes are]" like '[the number entered by the user]%' limit 5;
如果需要,这是服务器的完整代码(我更改了一些变量,添加了更多 cmets 等以澄清什么是什么):
const http = require('http');
const url = require('url');
const { Client } = require('../../../nodeModules/pg/node_modules/pg');
http.createServer(function (req, res) { //creating the http server from which the information can be extracted
const client = new Client({
user: "[the PostgreSQL user you're using to manage the database]",
password: "[password to your database]",
host: "localhost",
port: 5432,
database: "[the name of your database]"
});
res.writeHead(200, { 'Content-Type': 'text/html' });
res.writeHead(200, { "Access-Control-Allow-Origin": "*" });
try {
execIt();
async function execIt() { //creating an async function, it is important as otherwise await won't work
try {
var infoFromURL = url.parse(req.url, true).query; //
console.log("the Num: " + infoFromURL.need);
var neededNum1 = infoFromURL.need;
var neededNum = neededNum1.toString();
if ((neededNum.length > 5) || (neededNum.length == 5)) {
res.write("");
return res.end();
} else {
await client.connect(); //waits for the client to connect
console.log("Connected successfully.");
// the following line has the SQL code that'll be sent to the database
const { rows } = await client.query("select \"[name of the column in which the Zip Codes are]\" from \"[name of your table in the databse]\" where \"[name of the column in which the Zip Codes are]\" like \'[the number entered by the user]%\' limit 5;");
console.log(rows);
// from here to up till "return res.end();" line the entire code is just to print out the data recovered from the database
var toPrint = "[";
for (var i = 0; i < 5; i++) {
if (i == 4) {
toPrint = toPrint + "\"" + rows[i].zip.toString() + "\"" + "]";
} else {
toPrint = toPrint + "\"" + rows[i].zip.toString() + "\"" + ", ";
}
}
console.log(toPrint);
res.write(toPrint);
await client.end();
console.log("Client disconnected successfully.");
return res.end();
}
} catch (ex) {
console.log(`Something wrong happend ${ex}`);
}
}
} catch (error) {
console.log(error);
}
}).听(8096);
console.log('服务器运行在http://127.0.0.1:8096/');
由于您可能没有使用 PostgreSQL,甚至可能没有使用 nodeJS,您可以忽略上面的代码,但如果您愿意,它可能会有所帮助。
这基本上发送了与用户输入的邮政编码部分最相似的前 5 个邮政编码。
zipChanged() 函数的以下部分是收集发回的信息并对其进行排序。
zipPossibilities_G = JSON.parse(this.responseText);
fillZipPossibilities();
这里的数组 zipPossibilities_G(它是一个全局数组)收集 nodeJS 服务器发回的文本到 html 文件,函数 fillZipPossibilities() 是填充选项。
fillZipPossibilities() 是这样的:
function fillZipPossibilities() {
for (var i = 0; i < 5; i++) {
document.getElementById(zipOptionArr_G[i]).value =
zipPossibilities_G[i];
}
}
这里 5 个 <option> 标记中的每一个都填充了发回的文件。 zipOptionArr_G 数组是另一个全局数组,它具有 5 个 <option> 标签的 id,如下所示
var zipOptionArr_G = ["zipOption1", "zipOption2", "zipOption3", "zipOption4", "zipOption5"];
我希望我正确理解了这个问题,并且这对您有所帮助