gpt4 book ai didi

javascript - 不明白为什么 ajax 不直接更新我的按钮

转载 作者:行者123 更新时间:2023-11-28 02:31:57 25 4
gpt4 key购买 nike

我的 ajax 的目标是关注和取消关注某人。问题是,当我单击按钮时,会发送请求,但我需要将页面刷新到新按钮,而不是在下面看到它。如何确保它无需刷新即可直接工作。

<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>

这里是生成按钮的 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>

最佳答案

您可以在调用 ajax 方法之前获取按钮的句柄,而不是使用从服务器返回的值来获取按钮的句柄(因为您已经在按钮对象的范围内)。像这样:

<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>

我还没有测试过这段代码,但它应该可以工作

关于javascript - 不明白为什么 ajax 不直接更新我的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14009711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com