[英]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). 我有一个属性
weight.subtotal
,我想在其更改时自动对其进行更新(通过模型上的before_save回调进行更新)。
I looked at pjax, but that seems too heavy. 我看着pjax,但这看起来太沉重了。 All I want to happen is, once that gets changed, the one
td
or div
that has this: 我要发生的就是更改后的一个
td
或div
,它具有以下内容:
<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. 编辑1:最好是“就地最佳”之类的宝石,但它不是依靠用户更新值,而是侦听值是否已更改-并且当它更改时,它只会更新页面上的该值。 。
Couldn't come up with any gem, so its all from scratch, it needs a method that returns the current value, something like, 无法提供任何gem,因此从头开始,它需要一个返回当前值的方法,例如,
/weights/get_subtotal/:id.:format
I'd recommend just spit it out in json so it can be easily interpreted by jquery. 我建议只是将其吐入json中,以便jquery可以轻松解释。
Then you poll that method using jquery, and if it has been changed, change the value in the view, like so. 然后,使用jquery轮询该方法,如果已更改,请像这样更改视图中的值。
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, 如果您将权重的ID放在td的ID中会很容易,例如,
<td id="weigth_<%= weight.id%>"><%= weight.subtotal %></td>
hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.