2014-10-08 31 views
0

我有一個jQuery這樣的代碼:把PHP呼應成一個按鈕的innerHTML不起作用

$("#erase").click(function(){ 
     $("#erase").attr("disabled", "disabled"); // Prevent double-clicking 
     $(this).html("Erasing..."); 
     $.post("erase.php", {target: $("#target").val(), criteria: $("#criteria").val()}, function(data){ 
      $(this).html(data); // Change the button's caption to whatever erase.php echoes. 
      setTimeout(function(){ 
       window.location.href = "index.php"; 
      }, 3000); 
     }); 

targetcriteria都是HTML input標籤和按鈕被聲明爲button標籤。 我期待,當用戶點擊這些按鈕會發生:

  1. 按鈕將顯示爲灰色和它的文本會說「擦除......」
  2. erase.php將通過AJAX調用。 erase.php將從數據庫中刪除一行,並需要幾秒鐘才能完成。
  3. 當AJAX調用完成時,按鈕文本將是erase.php的輸出。這將是「成功」或「失敗」
  4. 3秒鐘後,用戶將被帶回主頁。

但在我的情況下,第3步失敗。按鈕陷在「擦除......」(請求確實完整的,但是。)


附註:我真的不能相信對於這個問題更好的稱號。如果你能爲我提出一個。請在評論中告訴我。我會很感激。

+0

控制檯中的任何錯誤消息? – Gowri 2014-10-08 03:50:02

+0

@Gowri控制檯中沒有錯誤。 – starleaf1 2014-10-08 03:52:17

+0

提供警報消息以檢查響應。 'alert(data);'在$(this).html(data)之前; ' – Gowri 2014-10-08 03:54:01

回答

5

$(this)裏面的$ .post不是你以前的版本。試試這種方式

$("#erase").click(function(){ 
    $("#erase").attr("disabled", "disabled"); // Prevent double-clicking 
    $(this).html("Erasing..."); 
    $this = $(this); 
    $.post("erase.php", {target: $("#target").val(), 
      criteria: $("#criteria").val()}, function(data){ 
      $this.html(data); 
      setTimeout(function(){ 
       window.location.href = "index.php"; 
      }, 3000); 
     }); 
+1

Cheery是正確的。您在回調函數內嘗試引用的「this」超出範圍。一旦進入新函數,我相信你所引用的「this」是函數本身 - 在JS中是一個對象。 在cheery的示例中,您正在創建一個新的變量,該變量在範圍內可以訪問。 總之,這不是這個曾經是。 – picus 2014-10-08 04:05:17

+0

對函數是對象的信息+1。 – starleaf1 2014-10-08 04:51:29