Rails link_to:确认后做一些事情 [英] Rails link_to: Do something after confirmation
问题描述
我正在尝试使用 link_to
执行通过AJAX执行保存操作:
I'm trying to execute a save action via AJAX using link_to
:
<%= link_to 'Save', image_path(image), method: :patch,
data:{ confirm: 'Save image?', remote: true } %>
我希望用替换链接< span>保存.. 。< / span>
确认后,但无法找到一个干净的方法。
I want the link to be replaced with <span>Saving...</span>
on confirmation, but can't figure out a clean way to do it.
现有解决方案的问题:
disable_with:
如果我添加:disable_with => '< span>保存...< / span>'
将替换链接的内部HTML而不是链接本身。不要那样。
disable_with:
If I add :disable_with => '<span>Saving...</span>'
the inner HTML of the link will be replaced instead of the link itself. Don't want that.
onclick:
如果我添加:onclick => ; $(this).replaceWith('< span> Saving ...< / span>');
该链接将立即被替换,即使用户取消确认
onclick:
If I add :onclick => "$(this).replaceWith('<span>Saving...</span>');"
the link will be replaced immediately, even if the user cancels the confirmation
是否有适合Rails 3 UJS最佳实践的解决方案?
Is there a solution that fits with Rails 3 UJS best practices?
推荐答案
您可以使用钩子 ajax:beforeSend
:
$('a#my_link_to').bind('ajax:beforeSend', function(evt, xhr, settings) {
$(this).replaceWith('<span>Saving...</span>');
})
然后你可以添加绑定到 ajax :成功
:
And then you could add a bind to ajax:success
:
$('a#my_link_to')
.bind('ajax:beforeSend', function(evt, xhr, settings) {
$(this).replaceWith('<span id="saving">Saving...</span>');
})
.bind('ajax:success', function(evt, data, status, xhr) {
$('span#saving').replaceWith('Saved!');
})
N注意:请参考以下评论,这也非常重要
Note: Please refer the comment below which also is very important
这篇关于Rails link_to:确认后做一些事情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!