简体   繁体   中英

How do I update one attribute using AJAX without having to use any heavy JS?

I have an attribute weight.subtotal that I want to automagically update anytime it changes (it gets updated with a before_save callback on the model).

I looked at pjax, but that seems too heavy. All I want to happen is, once that gets changed, the one td or div that has this:

<td><%= weight.subtotal %></td>

To be automagically updated with no page reload.

Thanks.

Edit 1: Preferrably a gem like 'best-in-place', but rather than relying on the user to update the value, it listens to see if the value has changed - and when it does, it updates just that value on the page.

Couldn't come up with any gem, so its all from scratch, it needs a method that returns the current value, something like,

/weights/get_subtotal/:id.:format

I'd recommend just spit it out in json so it can be easily interpreted by jquery.

Then you poll that method using jquery, and if it has been changed, change the value in the view, like so.

function poll(){
    setTimeout(function(){
        $.ajax({ url: "/weights/get_subtotal/xx", success: function(data){

            //put code here to compare old td value 
            //with current value, and replace if different

            //Setup the next poll recursively
            poll();
        }, dataType: "xxxxx"});
    }, 10000);
};
$(document).ready(function(){
    poll();
});

if would be easy if you just put the id of weights in the id for the td, something like,

<td id="weigth_<%= weight.id%>"><%= weight.subtotal %></td> 

hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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