简体   繁体   English

Rails / jQuery-通过数据库实时搜索

[英]Rails/ jQuery - searching live through database

I implemented a simple search while I feed to my database, so I can see if the record with the name already exists: 在馈入数据库时​​,我实现了一个简单的搜索,因此我可以查看名称是否已存在的记录:

function doneTyping() {
  $.ajax({
    url: $('#existance_route').val(),
    type: "GET",
    dataType: "json",
    data: { place_name: $name_input.val() },
    complete: function() {},
    success: function(data, textStatus, xhr) {
      setupTextfieldsAddonsWith(data);
      console.log("Response received!");
    },
    error: function() {
      console.log("AJAX error!");
    }
  });
};

setupTextfieldsAddonsWith(data) just simply tell the user (by the UI) that a records exists or not. setupTextfieldsAddonsWith(data)只是简单地(通过UI)告诉用户记录是否存在。

However I have an issue. 但是我有一个问题。 Sometimes when I go to the link to create a new record, it just doesn't work. 有时,当我转到链接以创建新记录时,它根本无法工作。 But then I reload the page manually and it starts working. 但是,然后我手动重新加载页面,它开始工作。

Does anyone have any idea why I receive such behavior? 有谁知道为什么我会收到这种行为?

PS. PS。 If there are "wiser" plugins for doing the thing that I describe please let me know. 如果有用于执行我所描述的操作的“更明智”的插件,请告诉我。 I only found Client Side Validations but it is now exactly what I need to do 我只找到了客户端验证,但现在正是我需要做的

EDIT 编辑

This is how I trigger doneTyping (code from one of the SO questions): 这就是我触发doneTyping的方式(SO问题之一的代码):

var typingTimer;
var doneTypingInterval = 500;
// place_name is an id bind to a text_field
$('#place_name').on('keyup', function() {
  clearTimeout(typingTimer);
  typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

$('#restaurant_name').on('keydown', function () {
  clearTimeout(typingTimer);
});

Ok, so I did some more research and found this: click 好的,所以我做了更多研究,发现了这一点: 单击

Basically adding my functions inside 基本上在里面添加我的功能

$(document).on('turbolinks:load', function() {

  ...your javascript goes here...

});

makes everything work as expected! 使一切正常工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM