2015-06-27 72 views
0

如果ajax失敗,我想返回我的按鈕值。

這HTML(PHP的):

<a href="javascript:void(0);" id="follow-topic" value="7"> 
    <button class="btn btn-xs btn-primary pull-right"><?php echo $_LANGS['forum']['follow']; ?></button> 
</a> 

這個js(在PHP):

$("#follow-topic").click(function(event) { 
     var topicid = $(this).attr('value'); 
     var button_follow_html = $(this).html(); 
     if ($(this).is("a[disabled]")){ return false; } 
     $("#follow-topic button").html('<?php echo $_LANGS['system']['loading_button']; ?>'); 
     $(this).attr({ disabled: true}); 
     $.ajax({ 
      url: "", 
      data: { follow_topic: topicid }, 
      type: "POST", 
      success: function (data) { 
       $("#follow-topic").html(data); 
       $("#follow-topic").attr({ disabled: false}); 
      }, 
      error: function(data, button_follow_html) { 
       handleRequestError(data); 
       $("#follow-topic").attr({ disabled: false}); 
       $("#follow-topic").html(button_follow_html); 
      } 
     }); 
    }); 

我已經更改按鈕值$_LANGS['system']['loading_button']但我想回到$_LANGS['forum']['follow']如果阿賈克斯失敗或客戶端丟失連接。

該系統使用多種語言,如果ajax成功,按鈕將被替換爲後面的按鈕,所以我不能使用$("#follow-topic button").html('<?php echo $_LANGS['forum']['follow']; ?>');

對不起,我的英語,謝謝

回答

1

jQuery documentation,如果AJAX調用失敗叫error函數有3個參數:

錯誤

類型:Function(jqXHR jqXHR,字符串textStatus ,String errorThrown)

所以你實際上得到textStatusbutton_follow_html變量響應此代碼:

 error: function(data, button_follow_html) { 
      handleRequestError(data); 
      $("#follow-topic").attr({ disabled: false}); 
      $("#follow-topic").html(button_follow_html); 
     } 

的參數是optionnal,所以不是你可以做:

 error: function(data) { 
      handleRequestError(data); 
      $("#follow-topic").attr({ disabled: false}); 
      $("#follow-topic").html(button_follow_html); 
     } 

button_follow_html不會被重新定義,將仍然有相同的值在ajax調用之前,您可以按原樣使用它。