簡體   English   中英

不明白為什么ajax不直接更新我的按鈕

[英]don't understand why ajax isn't updating my button directly

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

我尚未測試此代碼,但它應該可以工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM