键入时预先键入不调用搜索

键入时预先键入不调用搜索

本文介绍了键入时预先键入不调用搜索 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用 mysql 在 nodejs 中实现预先输入搜索,但无法弄清楚我的代码有什么问题.

trying to implement the typeahead search in nodejs with mysql, but can't figure out what's wrong in my code.

手动转到 http://localhost:5000/search?key=s 时例如,我可以在控制台中看到结果和调试日志.但是当输入输入文本时,它没有显示任何内容,也看不到控制台中的 console.log("debug") 所以看起来/search 甚至没有被调用

When manually going to http://localhost:5000/search?key=s for example, I can see the result and my debug logs in the console. but when typing in the input text, it's not showing anything nor can't see the console.log("debug") in the console so looks like the /search is not even called

现在我可以访问 API 回调并获得我的调试日志,我可以在执行 console.log(data) 时看到结果,但屏幕上没有显示任何内容,没有包含建议列表的下拉列表数据,我也有这个错误:

now I can get to the API callback and have my debug logs, I can see the result when doing console.log(data) but nothing is displayed on the screen, there is no dropdown with the list of suggestion within data and I also have this error :

未捕获的类型错误:无法使用 'in' 运算符在 ["Sep

Uncaught TypeError: Cannot use 'in' operator to search for '4' in ["Sep

有什么想法吗?asyncResults(data) 有问题吗?

Any ideas ? something wrong with the asyncResults(data) ?

这是我的代码:

index.html:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>test</title>
    <script src="https://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript" src="assets/javascripts/typeahead.bundle.js"></script>
</head>

<body>
    <input class="typeahead tt-query" spellcheck="false" autocomplete="off" name="typeahead" type="text" />

    <script type="text/javascript">
        $(document).ready(function(){
            $('input.typeahead').typeahead({
                highlight: true,
            },
            {
            name: 'Name',
            display: 'value',
            source: function(query, syncResults, asyncResults) {
                $.get('/search?key=' + query, function(data) {
                    console.log(data)
                    asyncResults(data)
                });
            }
            })
        });
    </script>
</body>
</html>

App.js:

const express = require('express');
const fileUpload = require('express-fileupload');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const path = require('path');
const app = express();

const port = 5000;

// create connection to database
// the mysql.createConnection function takes in a configuration object which contains host,user, password and the database name.
const db = mysql.createConnection ({
host: 'localhost',
user: 'raid',
password: 'raid',
database: 'raid',
port: 3308
});

// connect to database
db.connect((err) => {
if (err) {
    throw err;
}
console.log('Connected to database');
});
global.db = db;



// configure middleware
app.use(express.static(__dirname + '/public'));
app.set('port', process.env.port || port); // set express to use this port
app.set('views', __dirname + '/views'); // set express to look in this folder to render our view
app.set('view engine', 'ejs'); // configure template engine
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // parse form data client
app.use(express.static(path.join(__dirname, 'public'))); // configure express to use public folder
app.use(fileUpload()); // configure fileupload

app.engine('html', require('ejs').renderFile)
// routes for the app

app.get('/raid', function(req, res){
    res.render('index.html');
})

app.get('/search', function(req, res){
    console.log("debug")
    db.query('SELECT Name from champions where Name 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].Name);
    }
    res.end(JSON.stringify(data));
    });
});


// set the app to listen on the port
app.listen(port, () => {
    console.log(`Server running on port: ${port}`);
});

推荐答案

解决了以下问题:

var Name = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: 'http://localhost:5000/search?key=%QUERY',
            wildcard: '%QUERY'
        }
        });

        $('#remote .typeahead').typeahead(null, {
        name: 'Name',
        displayKey: 'Name',
        source: Name,
        display: function(data) { return data.Name; }
    });

这篇关于键入时预先键入不调用搜索 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 20:09