使用Node.JS express和AJAX的JQuery自动完成

这是HTML:

<!DOCTYPE html> <html> <head> <link rel="shortcut icon" href="/favbar.png" /> <!-- JavaScript --> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" /> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script> <script type="text/javascript"> $(function () { $("#search").autocomplete({ source: function( request, response ) { $.ajax({ url: "/search", dataType: "jsonp", data: { featureClass: "P", style: "full", maxRows: 12, term: request.term }, success: function( data ) { response( $.map( data.results, function( item ) { return { label: item, value: item } })); } }); } }); }); </script> <script src="/stylesheets/bootstrap/js/bootstrap.min.js"></script> <!-- CSS --> <link href="/stylesheets/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen"> <link href="/stylesheets/bootstrap/css/bootstrap.css" rel="stylesheet" media="screen"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="/stylesheets/bootstrap/css/bootstrap-responsive.css" rel="stylesheet"> <link type="text/css" href="/stylesheets/bootstrapui/css/custom-theme/jquery-ui-1.10.0.custom.css" rel="stylesheet" /> </head> <body> <input type="text" id="search" class="search-query" placeholder="Search..." /> </head> </body> </html> 

这是node.js代码:

 app.post('/search', function (req, res){ var regex = new RegExp(req.body.term); usermodel.aggregate({$match: { user: regex }}, function (err, users){ if (err) throw err; var names = []; for (var nam in users) { names.push(users[nam].user); } var result = { results: names } res.json(result); }); }); 

此代码不起作用。 我得到完美的AJAX请求,问题是Node.js响应。 我不知道是回应的types,还是我发送的方式。 所有结果数组中的names ,我发送这样的{ result: names } 。 也许我应该只发送res.json(result) 。 在一些例子中使用GET请求,我使用POST,我应该改变? 我使用mongodb和mongoose作为数据库。

我怎样才能做到这一点? 感谢您的提前!

对于自动完成表单,我会推荐twitter typeahead 。 非常简单,易于使用和强大。

http://twitter.github.com/typeahead.js/examples/中的一些示&#x4F8B;

文档和代码: http : //twitter.github.com/typeahead.js