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

MrM*_*ado 1 ajax jquery mongoose node.js express

这是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>
Run Code Online (Sandbox Code Playgroud)

这是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);

    });

});
Run Code Online (Sandbox Code Playgroud)

此代码不起作用.我完全得到了AJAX请求,问题是Node.js响应.我不知道响应的类型或发送方式.names在包含所有结果的数组中,我发送它就像这样{ result: names }.也许我应该只发送res.json(result).在某些示例中使用GET请求,我使用POST,我应该更改吗?我使用mongodb和mongoose作为数据库.

我怎样才能做到这一点?谢谢你的进步!

Alf*_*nso 9

对于自动填充表单,我建议twitter typeahead.非常简单,易于使用和强大.

例如:http://twitter.github.com/typeahead.js/examples/

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