我正在使用Node.js + Express.js为Library数据库构建一个非常基本的搜索引擎。我的HTML有一个POST表单,可以向应用程序发送标题或关键字,以便在MySQL数据库中查询书籍/书籍。按标题搜索工作正常,但关键字让我很难过。见下文。
HTML
<form id="searchForm" action="" method="post">
<select class="form-control" id="searchType">
<option class="" value="0">Search by title</option>
<option class="" value="1">Search by keyword</option>
</select>
<select class="form-control" id="titles" name="titles">
<% for (var title in titles) {;%>
<option class=""><%=titles[title].TITLE%></option>
<% }; %>
</select>
<textarea class="form-control" name="keyword" contenteditable="false" id="keyword" placeholder="Enter keyword here..."></textarea> <!-- placeholder is only supported in a few browesers
(Firefox 3.7+, Chrome, Safari, IE 10). Could use
jQuery but ah-->
<input class="btn btn-default" type="submit" value="Search"></input>
</form> <!-- /searchForm -->
快递代码
app.post('/getBooksByTitle', function (req, res) {
connection.getConnection(function(err, tempCon) {
if (err) {
tempCon.release();
console.log('ERROR IN SQL CONNECTION!');
}
else {
console.log('CONNECTED TO SQL');
tempCon.query('SELECT * FROM BOOKS WHERE TITLE=?', req.body.titles, function(err, rows) {
if (err) {
console.log('BAD QUERY');
}
else {
console.log(req.body.titles);
res.json(rows);
}
tempCon.release();
});
}
});
});
app.post('/getBooksByKeyword', function (req, res) {
connection.getConnection(function(err, tempCon) {
if (err) {
tempCon.release();
console.log('ERROR IN SQL CONNECTION!');
}
else {
console.log('CONNECTED TO SQL');
tempCon.query('SELECT * FROM BOOKS WHERE (AUTHOR LIKE ? || TITLE LIKE ? || GENRE LIKE ? || DESCRIPTION LIKE ?)', '%' + req.body.keyword + '%', function(err, rows) {
if (err) {
console.log('BAD QUERY');
console.log(req.body);
}
else {
res.json(rows);
console.log(req.body.keyword);
}
tempCon.release();
});
}
});
});
我正在使用req.body.(field_name)
将表单数据拉到节点,但它似乎没有收集文本框。如果我console.log(req.body)
我只看到标题字段。我搞砸了哪里?
编辑:处理动作和一些动画的jQuery脚本。
$(document).ready(function () {
toggleFields(); //call this first so we start out with the correct visibility depending on the selected form values
//this will call our toggleFields function every time the selection value of our searchType field changes
$("#searchType").change(function () {
toggleFields();
});
});
//this toggles the visibility of our input fields depending on the current selected value of the searchType field.
//also it toggles the action of the submit form to the appropriete post call.
function toggleFields() {
if ($("#searchType").val() == 0) {
$("#searchForm").attr('action', '/getBooksByTitle');
$("#titles").slideDown();
$("#keyword").slideUp();
}
else {
$("#searchForm").attr('action', '/getBooksByKeyword');
$("#titles").slideUp();
$("#keyword").slideDown();
}
}
答案 0 :(得分:0)
感谢您尝试提供的帮助。我通过将<textarea>
字段更改为<input>
字段来解决问题。现在帖子将我的标题和关键字发送回服务器。