2013-03-05 38 views
1

这是HTML:JQuery的自动完成与Node.js的表达和AJAX

<!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响应。我不知道是回应的类型,还是我发送的方式。 names在一个阵列中的所有结果,我发送它像这样{ result: names }。也许我应该只发送res.json(result)。在一些例子中使用GET请求,我使用POST,我应该改变它吗? 我使用mongodb和mongoose作为数据库。

我该怎么做?感谢提前!

+0

哪里是你的回应()函数? – chovy 2013-03-05 23:48:04

+0

它必须在哪里?我不知道你是在谈论节点服务器还是前端JS代码? – MrMangado 2013-03-06 19:29:07

回答