如何使用 mongoosastic + AJAX 进行即时搜索?

How to do instant search with mongoosastic + AJAX?

我已经成功配置了 mongoosastic,我尝试搜索并且它工作正常,但是当涉及到前端时,我不太确定如何实现这一点,我尝试了很多方法但不能'想不出好的办法。

这是代码。

// For the Search API
    router.post('/api/search/', function(req, res, next) {
      Job.search(
        {
          query_string:
          { query: req.body.search }
        } , function(err, results) {
            if (err) return next(err);
            res.json(results);
        });
    });

所以每当我搜索与 'engineer' 相关的内容时,我都会得到 json 数据

所以后端工作得很好。

然而,当谈到 jquery 和 ajax 时,我不断收到错误的请求

逻辑:无论什么时候插入东西,然后 post 然后找到那个结果。

这是前端 jquery 代码。

  $('#search').keyup(function() {

    var search_term = $(this).val();


    $.ajax({
      type: "POST",
      url: "/api/search",
      success: function(){
        $('search_results').html(search_term);
      },
      error: function(data){
        alert('Error', data);
      }
    });

  });

HTML

<input type="text" class="form-control input-lg" id="search" name="search" placeholder="Search for part-time..." />



 <div id="search_results">


    </div>

如何将 json 结果插入 search_results

你需要做的是

  1. 每次击键,获取输入值
  2. 通过 Ajax 将其发送到您的后端
  3. 使用JSON成功返回(这里我们只是在div中显示"title: salary")

因此您的前端代码将如下所示:

$('#search').keyup(function() {

  // 1. grab the search term from the input field
  var search_term = $(this).val();

  // 2. send it to your back-end via ajax in the body 
  $.ajax({
    method: "POST",
    url: "/api/search",            // <-- your back-end endpoint
    data: "search=" + search_term  // <-- what you're sending
    dataType: "json",              // <-- what you're expecting back
    success: function(json){       // <-- do something with the JSON you get
      // 3. parse the JSON and display the results
      var res = json.hits.hits.map(function(hit) {
          return hit._source.title + ": " + hit._source.salary;
      });
      $('search_results').html(res.join("<br />"));
    },
    error: function(data){
      alert('Error', data);
    }
  });
});

我现在正在做与此非常相似的事情。首先,看起来您在初始 ajax 请求中缺少参数,因此您的节点服务器未获取任何信息:

$('#search').keyup(function() {
//Perform the ajax request
var search_term = $(this).val();
$.ajax({
  type: "POST",
  url: "/api/search",
  data: {"search": search_term},
  success: function(data) {
     //Loop over all the data and output it, appending data to element
     //with a line break
     for(var i=0; i < data.hits.length; i++)
    $('search_results').append(data.hits[i]._source.title+'<br />');
  },
  error: function(data){
    alert('Error', data);
  }
});

});

在调试这些问题时,如果您可以访问它以查看它实际获取的数据,那么在我的节点服务器中使用 console.log() 对我非常有帮助:

// For the Search API
router.post('/api/search/', function(req, res, next) {
  console.log("%j", req.body.search)
  Job.search(
    {
      query_string:
      { query: req.body.search }
    } , function(err, results) {
        if (err) return next(err);
        res.json(results);
    });
});

日志会非常清楚地报告未定义或您期望的正确字符串,这样您就可以查看您的参数是否正确

您可能还想检查您的节点服务器地址和端口(就像完整性检查一样)。对于我的 ajax 请求,我必须输入

url: "http://localhost:9200/api/search" 

在我的查询前面只是因为我的服务器在不同的端口上

这里有一些关于jQuerypost函数的更多信息供您参考:

http://api.jquery.com/jquery.post/

希望对您有所帮助!