我正在尝试使用Node&Handlebars渲染为数据库添加搜索功能。但是,当我现在搜索时,它给我一个404错误,为什么它不显示搜索结果?这是我的路线信息

        function searchPokemon(res, mysql, context, searchinput, complete){
        var inserts = [req.body.searchinput];
        var sql = 'SELECT pokemonname FROM pokemon WHERE pokemonname LIKE "%' + inserts + '%';
        mysql.pool.query(sql, inserts, function(error, results, fields){
                if(error){
                        res.write(JSON.stringify(error));
                        res.end();
                }
                context.search = results;
                complete();
                });
        }


   router.get('/search', function(req, res){
        callbackCount = 0;
        var context = {};
        var mysql = req.app.get('mysql');
        searchPokemon(res, mysql, context, req.body.searchinput, complete);
        function complete(){
                callbackCount++;
                if(callbackCount >= 1) {
                        res.render('search-pokemon', context);
                }
        }
});


这是我当前在(pokemon.handlebars)上呈现搜索功能的页面

<h1>Current Pokemon Moves -</h1>

<table id="table">
    <thead>
        <th>Pokemon Name </th>
        <th>Evolution Level   </th>
        <th>Move Name   </th>
        <th>Strength</th>
    </thead>
   <input type="text" class="search form-control" name="searchinput" placeholder="Pokemon Name">
   <input type="button" class="btn btn-primary" value="Search" onclick="getUsers({{searchinput}})">
        <br>


这是我要搜索的脚本

function getUsers(searchinput){
        $.ajax({
                url: '/search-pokemon',
                type: 'GET',
                success: function(result){
                        window.location.reload(true);
                }
        })
};

最佳答案

我在搜索功能上遇到了同样的问题,并且使用了typeahead.js。
我使用的是“ get”而不是“ post”

    router.post('/search', function(..)..


我将我的代码放在这里,以便您有所了解。

app.js

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

// search function
app.post('/search',function(req,res){
    var str = {
        stringPart:req.body.typeahead
    }

    db.query('SELECT songTitle FROM song WHERE songTitle LIKE "%'+str.stringPart+'%"',function(err, rows, fields) {
        if (err) throw err;
        var data=[];
        for(i=0;i<rows.length;i++)
        {
            data.push(rows[i].songTitle);
        }
        res.send(JSON.stringify(data));
    });
});


index.ejs

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../JS/jquery.typeahead.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
    $('input.typeahead').typeahead({
    name: 'typeahead',
    remote: 'http://localhost:3000/search?key=%QUERY',
    limit: 10
    });
    });
</script>

<form method="POST" action="/search">
<label>Search Data</label>
<input class="typeahead tt-query" spellcheck="false" autocomplete="off" name="typeahead" type="text" />
</form>

10-06 04:18
查看更多