jquery – 如何使用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);
        });
    });

因此,每当我搜索与“工程师”相关的内容时,我都会得到一个json数据

enter image description here

所以后端确实完美运行.

但是当涉及到jquery和ajax时,我总是得到不好的请求

逻辑:每当插入某些内容然后发布并找到该结果.

这是前端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

如何将json结果插入search_results?

最佳答案
你需要做的是

>在每个键击中,获取输入值
>通过Ajax将其发送到您的后端
>使用你成功时获得的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",// <-- 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("

相关文章

1.第一步 设置响应头 header(&#39;Access-Control-Allow...
$.inArray()方法介绍 $.inArray()函数用于在数组中搜索指定的...
jquery.serializejson.min.js的妙用 关于这个jquery.seriali...
JS 将form表单数据快速转化为object对象(json对象) jaymou...
jQuery插件之jquery.spinner数字智能增减插件 参考地址:http...