gpt4 book ai didi

javascript - 如何使用nodejs mysql从html表单传递id

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:32 28 4
gpt4 key购买 nike

这是一个 html 表单,我可以通过下拉列表输入客户端 ID,我想使用来自下拉列表的客户端 ID 来传递表单:

<form action="/query" method="get">

<!-- <label>Client ID</label> -->
<select name="client_id" required="">
<option disabled selected value> -- select a Client -- </option>
<%for(i=0; i<clients.length; i++){%>
<option value="<%= clients[i].id%>"><%= clients[i].client_name %></option>
<%}%>
</select>
<button type="submit">Submit</button>
</form>

这是获取函数:

    // Query
app.get('/query', function(req, res){
/* var client_id = {
client_id:req.body.client_id,
};*/
db.query("SELECT * FROM regions WHERE client_id = client_id ",function(err, result){
if(err) throw err;
//console.log(rows);
console.log(result);
res.render('query_areas',{result:result});
});
});

最佳答案

由于它是 GET 请求,因此可以通过 req.query.client_id 访问客户端 ID。

要将其传递给 SQL 查询,您可以使用 query placeholder :

app.get('/query', function(req, res){
db.query("SELECT * FROM regions WHERE client_id = ?", [ req.query.client_id ], function(err, result) {
if(err) throw err;
//console.log(rows);
console.log(result);
res.render('query_areas',{result:result});
});
});

如果您想使用 POST,则应使用 req.body.client_id (确保您还使用 body-parserexpress.json 和/或 express.urlencoded 等主体解析器中间件),否则 req.body 将不会被创建)。

关于javascript - 如何使用nodejs mysql从html表单传递id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53984761/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com