如何做到即时搜索与mongoosastic + AJAX? [英] How to do instant search with mongoosastic + AJAX?

查看:446
本文介绍了如何做到即时搜索与mongoosastic + AJAX?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经配置mongoosastic成功,我试图寻找它工作正常,但是当涉及到​​前端的我真的不知道如何做到这一点,我尝试了很多方法,但迟迟不来了一个很好的解决方案。

I have configured mongoosastic successfully, I tried searching and it is working fine, but when it comes to front-end I'm not really sure on how to achieve this, I experimented with a lot of ways but couldn't come up with a good solution.

这里的code。

// 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);
        });
    });

所以当我寻找的东西,是关系到'工程师',我会得到一个JSON数据

So whenever I search something that is related to 'engineer', I will get a json data

输入图像的描述在这里

因此​​,后端也可以正常使用。

So the backend does working perfectly.

然而,当涉及到jQuery和AJAX我不断收到错误的请求

However when it comes to jquery and ajax I keep getting bad request

的逻辑:不管什么时候插入,然后张贴和发现的结果。

The logic: whenever something is inserted then post that and find that result.

下面是前端的jQuery code。

Here's the frontend jquery code.

  $('#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

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)

所以前端code是这样的:

So your front-end code would look like this:

$('#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);
    }
  });
});

这篇关于如何做到即时搜索与mongoosastic + AJAX?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆