Typeahead не вызывает API поиска при наборе текста - PullRequest
0 голосов
/ 18 июня 2020

пытается реализовать поиск с опережением ввода в nodejs с помощью mysql, но не может понять, что не так в моем коде.

При ручном переходе к http://localhost: 5000 / search ? key = s например, я могу видеть результат и свои журналы отладки в консоли. но при вводе вводимого текста он ничего не показывает и не видит console.log ("отладка") в консоли, поэтому похоже, что / search даже не вызывается

EDIT: теперь я могу перейти к обратному вызову API и получить мои журналы отладки, я вижу результат при выполнении console.log (data), но на экране ничего не отображается, нет раскрывающегося списка со списком предложений в данных, и у меня также есть эта ошибка:

Uncaught TypeError: Невозможно использовать оператор 'in' для поиска '4' в ["Sep

Есть идеи? Что-то не так с asyncResults (данными)?

здесь это мой код:

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}`);
});

1 Ответ

0 голосов
/ 23 июня 2020

решил проблему следующим образом:

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; }
    });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...