首页 > 解决方案 > 为什么在 Node.JS 上使用 typeahead 的 LiveSearch 不检索数据

问题描述

我有一个使用 Express.Js 和 Node.Js 创建的应用程序。我在这一步中想要实现的是对数据库进行实时搜索。我对路由中的顺序有点困惑,我不确定是否必须在 router.get 中包含搜索查询,或者是否必须在此之后创建一个 app.get。我的主页(索引)称为 user.js(我放置路由的地方),它从 http://localhost:3000/user 开始,我可以打开该页面,但是,我得到的结果是空白的。

您可以在此处找到与我的问题相关的问题Typeahead not call search API when typing

基本上,我可以在 http://localhost:3000/user/search?key= 中看到我的结果,但没有显示在主页中。

用户.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>

标签: htmlmysqlnode.jsexpressejs

解决方案


在 user.js 中更改此行

app.get('/search',function(req,res){

进入

router.get('/search', function(req,res){

对于 html 使用 Bloodhound 和 typeahead 函数应该是这样的:

var skus = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  //prefetch: '../data/films/post_1960.json',
  remote: {
    url: 'http://localhost:3000/user/search?key=%QUERY',
    wildcard: '%QUERY'
  }
});
$(document).ready(function(){
    $('input.typeahead').typeahead(
    {hint: true,
      highlight: false,
      minLength: 1
    },
    {
        name: 'sku',
        //remote: 'http://localhost:3000/user/search?key=%QUERY',
        source: skus,
        limit: 10
    });
});

推荐阅读