How to convert this observe_field to jquery

2020-07-25 12:50发布

问题:

I would like to use jquery instead of prototype and I am a bit lost to convert this observe_field in jquery.

<%=text_field_tag :section %>
<%= observe_field(:section, 
                  :frequency => 0.1, 
                  :update => "article_list",
                  :with => 'section', 
                  :url =>{ :action => :get_article_list }) %>

Here is my start:

$(document).ready(function() {
  $("#section").bind("keyup", function() {
    var url = '/catalogs/get_article_list';
    $.get(url, function(html) {
      $("#article_list").html(html);
    });
  });
});

I read this post but I think I'm missing something.

Would appreciate any explanations.

Thanks.

回答1:

An observer, observers an event on any input element, when the event occurs it send a request to given url using ajax and update response on page in given element.

Here you got the event observing very well, so you have written the code to bind the keyup event of section element.

Now when the keyup event triggers you need to make an ajax request to server.

 $(document).ready(function() {
   $("#section").bind("keyup", function() {
   data = {this.name: this.val()}; // the value of input that need to send to server
   $.get(url, data, // make ajax request
     function(html) { // function to handle the response
      $("#article_list").html(html); // change the inner html of update div
     });
   });
 });

Hope this helps you to understand it.



回答2:

This is also a good solution: https://github.com/splendeo/jquery.observe_field



回答3:

$(function() {
    // Executes a callback detecting changes
    $("#section"").change(function(){
    jQuery.ajax({data:'name=' + this.value, success:function(request){jQuery('#article_list').html(request);}, url:'/catalogs/get_article_list'
  })});});