首页 > 解决方案 > 如何使用 nodejs 和 ajax 使 typeahead 显示来自 mysql 的信息

问题描述

嗨,我正在尝试使用 typeahead 来使用 nodejs 和 express 显示本地数据库(Mysql)中的信息,但它不起作用

我已经尝试使用本教程https://codeforgeek.com/ajax-search-box-using-node-mysql/但它不起作用,我不知道我还能做什么

createSessions.js

router.get('/add/search', isLoggedIn, (req, res) =>
{
    dbConnection.query('SELECT fullname FROM pacientes WHERE fullname LIKE ?"%' + req.query.key + '%"',
        (err, rows, fields) =>
        {
            if (err) throw err;
            var data = [];
            for (i = 0; i < rows.length; i++)
            {
                data.push(rows[i].fullname);
            }
            res.end(JSON.stringify(data));
        }
    );
});

阿贾克斯

$(document).ready(function ()
{
    $('input.typeahead').typeahead(
    {
        name: 'paciente',
        remote: 'http://localhost:3000/createSesiones/add/search?key=%QUERY',
        limit: 10
    });
});

输入

<div class="form-group">
  <input type="text" class="form-control typeahead tt-query" name="paciente"
     placeholder="Asignar paciente" autofocus required>
</div>

我希望像这样工作,但显示来自我的数据库的信息

https://twitter.github.io/typeahead.js/

标签: mysqlnode.jsajaxexpresstypeahead.js

解决方案


您也可以使用以下查询进行节点 js + mysql 自动完成搜索

    db.query('SELECT country_name FROM countries WHERE country_name LIKE "%' + req.query.term + '%"',
    function(err, rows, fields) {
        if (err) throw err;
        var data = [];
        for (i = 0; i < rows.length; i++) {
            data.push(rows[i].country_name);
        }
        res.end(JSON.stringify(data));
    });

推荐阅读