У меня есть приложение, созданное с использованием Express.Js и Node.Js. На этом этапе я пытаюсь добиться живого поиска в базе данных. Я немного запутался с последовательностью маршрутов, я не уверен, должен ли я включать запрос для поиска внутри router.get или после этого мне нужно создать app.get. Моя главная страница (индекс) называется user.js (где я размещаю маршруты) и начинается с http://localhost:3000/user. Я могу открыть страницу, однако результаты, которые я получаю, пусты.
вы можете найти вопрос, связанный с моим вопросом здесь Typeahead не вызывает API поиска ввод
По сути, я вижу свои результаты в http://localhost:3000/user/search?key=, но не отображается на главной странице.
User.Js
var express = require('express');
var router = express.Router();
var db=require('../database');
var url = require('url');
var app=express();
// another routes also appear here
router.get('/', function(req, res, next) {
var query3=function(callback){
var sql3='SELECT AUTO_INCREMENT as nextorder FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = "database" AND TABLE_NAME = "order_new"';
db.query(sql3, function (err, data, fields) {
if (err) throw err;
return callback(data);
});
}
query3(function(data){
console.log(data);
res.render('user', { data: data});
});
});
//Extract the keyword.
//Return the result depending on the keyword.
app.get('/search',function(req,res){
//call MySQL Query. and //extract key using req.query.key
db.query('SELECT sku FROM item_new WHERE sku like "%'+req.query.key+'%"',
function(err, rows, fields) {
if (err) throw err;
var data=[];
for(i=0;i<rows.length;i++){
data.push(rows[i].sku);
}
//form JSON response and return.
res.end(JSON.stringify(data));
});
});
Просмотр страницы
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="javascripts/typeahead.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input.typeahead').typeahead({
name: 'typeahead',
remote: 'http://localhost:3000/user/search?key=%QUERY',
limit: 10
});
});
</script>
<script>
$(document).ready(function () {
// Denotes total number of rows
var rowIdx = 0;
// jQuery button click event to add a row
$('#addBtn').on('click', function () {
// Adding a row inside the tbody.
$('#tbody').append(`<tr id="R${++rowIdx}">
<td class="row-index text-center">
<td></td>
<td><input class="typeahead tt-query" spellcheck="false" autocomplete="off" name="typeahead" type="text" placeholder="type Sku" /></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td class="text-center">
<button class="btn btn-danger remove"
type="button">Remove</button>
</td>
</tr>`);
});
// jQuery button click event to remove a row.
$('#tbody').on('click', '.remove', function () {
// Getting all the rows next to the row
// containing the clicked button
var child = $(this).closest('tr').nextAll();
// Iterating across all the rows
// obtained to change the index
child.each(function () {
// Getting <tr> id.
var id = $(this).attr('id');
// Getting the <p> inside the .row-index class.
var idx = $(this).children('.row-index').children('p');
// Gets the row number from <tr> id.
var dig = parseInt(id.substring(1));
// Modifying row index.
idx.html(`Row ${dig - 1}`);
// Modifying row id.
$(this).attr('id', `R${dig - 1}`);
});
// Removing the current row.
$(this).closest('tr').remove();
// Decreasing total number of rows by 1.
rowIdx--;
});
});
</script>
<body>
<div class="container pt-4">
<div class="table-responsive">
<table id="itemsTable" class="table table-bordered"><thead><tr>
<th>Quantity</th>
<th>Item</th>
<th>SKU</th>
<th>Item Name</th>
<th>Item Price</th>
<th>Subtotal</th>
<th>Cartons Scanned</th>
<th>Individually Scanned</th>
<th>Current Inventory</th>
<th>Location Selected</th>
<th>Image</th>
<th>Edit</th>
</tr></thead>
<tbody id="tbody" contenteditable>
</tbody>
</table>
</div></div>
<br>
<button class="btn btn-md btn-primary"
id="addBtn" type="button">
Add new Row
</button>
</body>