2013-10-14 73 views
1

我有兩個AJAX功能看起來像這樣:ajax調用後重置變量?

$("body").on("click", ".follow", function() { 
    var followingId = $(this).data("following"); 
    var followData = {"following_id" : followingId} 
    $(this).addClass('disabled'); 
    $.ajax({ 
     url: "https://stackoverflow.com/users/follow/", 
     type: "POST", 
     data: followData, 
     dataType: 'json', 
     context: this, 
     error: function() {}, 
     success : function (response) { 
    $(this).addClass('unfollow'); 
    $(this).attr('data-unfollow', response.row_id); 
    $(this).removeClass('follow'); 
     } 
    }); 
    }); 

    $("body").on("click", ".unfollow", function() { 
    var unfollowId = $(this).data("unfollow"); 
    var unfollowData = {"row_id" : unfollowId}; 
    $(this).addClass('disabled'); 
    $.ajax({ 
     url: "https://stackoverflow.com/users/unfollow/", 
     type: "POST", 
     data: unfollowData, 
     context: this, 
     error: function() {}, 
     success : function() { 
     $(this).removeClass('disabled'); 
     $(this).addClass('follow'); 
     $(this).removeClass('unfollow'); 
     } 
    }); 
    }); 

當我「跟隨」的用戶,我得到了「ROW_ID」(讓我們說ROW_ID N°1)作爲響應,並設置爲取消關注數據。如果我「取消關注」用戶,則發送row_id n°1。這是正常的。

如果我再試一次,我會得到一個新的row_id(讓我們假設第2行)作爲響應。這也很正常。但是,如果我想再次取消關注,則會發送row_id n°1! 我想我應該更新

var unfollowId = $(this).data("unfollow"); 

(HTML中的值已更改爲ROW_ID N°2),但是當我張貼ROW_ID N°1被髮送。

我可以做到這一點嗎?

非常感謝!

+2

不能告訴你在問什麼。 – jfriend00

+1

當我使用第一個函數時,我得到一個row_id作爲響應。我將其設置爲數據屬性。如果我重用第一個函數,我得到一個新的row_id,我將其設置爲data屬性,但如果我使用第二個函數,則發送的row_id仍然是第一個函數。 – Ziplo

回答

1

在第一個功能,改變這種:

$(this).attr('data-unfollow', response.row_id); 

這樣:

$(this).data('unfollow', response.row_id); 

僅供參考,您可以使用jQuery鏈等等一系列這樣的:

$(this).removeClass('disabled'); 
$(this).addClass('follow'); 
$(this).removeClass('unfollow'); 

可以像這樣更有效地完成:

$(this).removeClass('disabled').addClass('follow').removeClass('unfollow'); 

或者,如果你喜歡他們在不同的行:

$(this).removeClass('disabled') 
    .addClass('follow') 
    .removeClass('unfollow'); 
+0

霍莉莫莉它工作!非常感謝 !你能解釋一下這個區別嗎? – Ziplo

+0

@Ziplo - 我沒有100%確定的解釋沒有一些調試。我知道使用'.data()'讀/寫更簡單,更安全。這可能是因爲你不能使用'.attr()'來寫這樣的自定義屬性。你可能不得不使用'.prop()',但無論如何'.data()'更適合這種用途。此外,請查看我添加到我的答案的其他提示。 – jfriend00

+0

我用「;」連結;因爲我可以有10/11一個更清晰。執行有區別嗎? – Ziplo