2015-09-20 161 views
0

按钮onclick看起来像这样onclick="return confirm('Are you sure to delete this item?')"。即使点击取消,帖子仍然被删除。onclick取消按钮仍然呼叫ajax

然后在jquery中。

$(document).ready(function(){ 
    $('.btn').click(function(event){ 
    event.preventDefault(); 
     $a = $(this).text().trim(); 
     if ($a == "Delete") 
     { 
      var postid = $(this).next('.postid').val(); 
      $(this).closest(".todo-content").fadeOut('slow'); 
      $.ajax({ 
       type: "POST", 
       url: BASE_URL+'classes/deletepost', 
       dataType: 'json', 
       data: {postid: postid}, 
       async: false, 
       success: function(data) { 
       }, 
       error: function(xhr, status, error) { 
        // check status && error 
      } 
     }); 
     } 
    }); 
}); 

如果点击确认中的取消,是否有取消对ajax的调用?

+0

我建议不要使用按钮的文本来确定它的行为。另外,不要使用同步Ajax。 –

+0

是的,我已经修好了。忘了删除这个问题哈哈。我想我仍然必须选择最好的答案 – iamdevlinph

回答

3

为什么不简单地从两个地方的事件转移到一个呢?将确认从HTML中移出并放入您的javascript中,如下所示:

$(document).ready(function(){ 
    $('.btn').click(function(event){ 
     if (!confirm('Are you sure to delete this item?')) 
     return; 

     event.preventDefault(); 
     /* code to delete here */ 
    }); 
}); 
0

修改代码以将确认内容包含在javascript中而不是内联中。

$('.btn').click(function(event){ 
if(!confirm('Are you sure to delete this item?')) 
return; 
    event.preventDefault(); 
... 
... 
... 
0

完全取出onclick,和函数中构造代码:

function deleteItem() { 
    if (confirm('Are you sure to delete this item?')) { 
     // code to delete... 
    } 
} 

$(document).ready(function(){ 
    $('.btn').click(function(event){ 
     deleteItem(); 
    }); 
}); 
0

我认为,你可以使用它像这样

在阿贾克斯功能后{event.preventDefault( );} This line add below

if(!confirm(“Are you sure”))return;

0

如果点击取消 确认,是否有取消对ajax的调用?

是的,那是可能的。你可以把结果从confirm在一个变量:

onclick="doDelete=confirm('Are you sure to delete this item?');" 

在jQuery代码,您可以检查变量的值:

$(document).ready(function(){ 
    $('.btn').click(function(event){ 
    event.preventDefault(); 
    if (doDelete) { 
     ... 
    } 
    }); 
}); 

然而,作为可能并不意味着它是最佳方案。最明显的解决方案是在jQuery代码中调用confirm