[英]don't understand why ajax isn't updating my button directly
The goal of my ajax is to follow and unnfollow someone . 我的ajax的目标是关注和取消关注某人。 The problem is that when i click on the button follow the resquest is send but i need to refresh the page to the new button Not following see it . 问题是,当我单击按钮时,将发送请求,但是我需要将页面刷新为新按钮。 How do i make sure that it work directly without refreshing. 我如何确保它可以直接工作而不刷新。
<script type="text/javascript">
$(function() {
$('.ajax_button').click(function() {
$.ajax({
type: "POST",
url: "/" +$(this).attr('name') + "/toggle_follow_via_ajax",
success: function(msg){
elm = $('#btn_' + msg);
if (elm.val() == "Stop Following") {
elm.val("Follow");
} else {
elm.val("Stop Following");
}
}
});
})
});
</script>
here is the html.erb that generate the button 这是生成按钮的html.erb
<div class="button_container">
<input type="button" name="<%= friend.username %>" id="btn_<%=friend.username %>" class="button ajax_button"
value="<% if current_user.is_friend? friend %>Stop Following<% else %>Follow<% end %>"/>
</div>
Instead of using the value returned from the server to get a handle to the button, you can get a handle to it before calling the ajax method (since you are already within scope of the button object). 不必使用服务器返回的值来获取按钮的句柄,而是可以在调用ajax方法之前获得它的句柄(因为您已经在按钮对象的范围之内)。 Like this: 像这样:
<script type="text/javascript">
$(function() {
$('.ajax_button').click(function() {
var btn = $(this);
$.ajax({
type: "POST",
url: "/" +$(this).attr('name') + "/toggle_follow_via_ajax",
success: function(msg) {
var val = btn.val() == 'Follow' ? 'Stop Following' : 'Follow';
btn.val(val);
}
});
})
});
</script>
I've not tested this code, but it should work 我尚未测试此代码,但它应该可以工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.