2014-10-08 27 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