我有一个使用jQuery Ajax和PHP删除记录的代码。我对用户拨打确认电话有疑问,经确认后再进行删除。我的确认函数在JAvascript中,我的ajax函数在jQuery中。然后,我应该如何合并这两个函数,以便首先警报将来,并且只有在确认Ajax函数应该执行时才会出现。对于你的参考,我把HTML放在我用来调用ajax函数和两个函数的下面: 请帮我解决这个问题。
HTML code:
<a id ="12002" href="#" class="c-icn c-remove delete_question" title="Delete question"> Delete</a>
Javascript确认功能:
<script language="javascript" type="text/javascript">
function ConfirmDelete() {
var ans=confirm("Are you sure to delete this question?");
if(!ans) {
return false;
}
}
</script>
JQuery Ajax功能如下:
$(function(){
$(document).on('click','.delete_question',function() {
var question_id = $(this).attr('id');
$(this).closest('tr').hide();
$.ajax({
type:'POST',
url:'match_question.php',
data:{'request_type':'ajax', 'op':'delete','question_id':question_id},
success: function(data) {
if(data=="YES") {
alert("Question has been deleted");
}
});
});
});
现在,您可以先帮助我调用确认功能,并且只有在收到用户确认时才执行进一步的ajax功能。提前谢谢。
答案 0 :(得分:5)
在jQuery单击处理程序中首先调用ConfirmDelete
方法...如果返回false返回并忽略其他步骤
$(function () {
$(document).on('click', '.delete_question', function () {
if (ConfirmDelete() === false) {
return;
}
var question_id = $(this).attr('id');
$(this).closest('tr').hide();
$.ajax({
type: 'POST',
url: 'match_question.php',
data: {
'request_type': 'ajax',
'op': 'delete',
'question_id': question_id
},
success: function (data) {
if (data == "YES") {
alert("Question has been deleted");
}
}
});
});
});
无需将其作为单独的函数编写,您可以将其简化为
$(function () {
$(document).on('click', '.delete_question', function () {
if (!confirm("Are you sure to delete this question?")) {
return;
}
var question_id = $(this).attr('id');
$(this).closest('tr').hide();
$.ajax({
type: 'POST',
url: 'match_question.php',
data: {
'request_type': 'ajax',
'op': 'delete',
'question_id': question_id
},
success: function (data) {
if (data == "YES") {
alert("Question has been deleted");
}
}
});
});
});
答案 1 :(得分:2)
您可以尝试在jquery函数中使用javascript函数:
$(function(){
$(document).on('click','.delete_question',function() {
var ans=confirm("Are you sure to delete this question?");
if(ans) {
var question_id = $(this).attr('id');
$(this).closest('tr').hide();
$.ajax({
type:'POST',
url:'match_question.php',
data:{'request_type':'ajax', 'op':'delete','question_id':question_id},
success: function(data) {
if(data=="YES") {
alert("Question has been deleted");
}
});
}
});
});