JQuery确认对话框,在按下提交按钮之后,但在使用.ajax()发布之前

JQuery confirmation dialog after pressing the submit button but before POSTing with .ajax()

本文关键字:ajax 布之前 按钮 对话框 确认 JQuery 提交 之后      更新时间:2023-09-26

我有一个非常简单的场景,我想使用JQuery的ajax()方法POST表单,但在实际执行POST之前执行请求来自用户的一些确认。

我有一个本地化按钮的JQuery UI对话框,以防你想知道下面所有的按钮代码是关于什么的。

这是我到目前为止的代码:

var i18n_deleteButtons = {};
i18n_deleteButtons[i18n.dialogs_continue] = function () {
    return true;
    $(this).dialog('close');
};
i18n_deleteButtons[i18n.dialogs_cancel] = function () {
    return false;
    $(this).dialog('close');
};
$('#delete-dialog').dialog({
    open: function () {
        $(this).parents('.ui-dialog-buttonpane button:eq(1)').focus();
    },
    autoOpen: false,
    width: 400,
    resizable: false,
    modal: true,
    buttons: i18n_deleteButtons
});
$("form#form_attachments").submit(function (event) {
    /* stop form from submitting normally */
    event.preventDefault();
    /* get some values from elements on the page: */
    var $form = $(this), url = $form.attr('action');
    // build array of IDs to delete (from checked rows)
    var jdata = { 'attachmentIdsToDelete': [] };
    $('input:checked').each(function () {
        jdata['attachmentIdsToDelete'].push($(this).val());
    })
    $.ajax({
        beforeSend: function (request) {
            // Return false if you don't want the form submit. 
            $('#delete-dialog').dialog('open');
        },
        url: url,
        type: "POST",
        dataType: "json",
        data: jdata,
        traditional: true,
        success: function (msg) {
            $('#msg').html(msg);
        }
    });
});

对话框实际上打开得很好,但点击任何按钮都不会发生任何事情。无论点击哪个按钮,该帖子都不会发生,对话框也不会关闭。

我怎样才能使它工作?

为什么不在提交处理程序中移动实际的ajax调用,并在删除对话框中按下按钮时触发它呢?

您可以将ajax调用存储在单独的函数中,并将该函数和url作为参数传递给确认例程。

 [pseudo code]
 function callAjax() {
     ...
 }
 function submitHandler() {
     confirmDialog({callback:callAjax,param:you_url});
 }
 function confirmDialog(obj) {
     $('#yes_btn').click(function() {
         // call the callback
         obj.callback(obj.param);
     });
     $('#no_btn').click(function() {
        // just close the dialog
     });
 }

这样,confirmDialog就不必知道ajax调用的任何信息,它只会在用户单击ok时使用给定的参数执行回调。

因为默认的jquery UI对话框对于常规使用和在一些自定义场景中配置有点麻烦,我环顾四周,发现了这个基于jquery UI默认内容的Easy Confirm插件。它还允许非常简单的国际化。

https://github.com/wiggin/jQuery-Easy-Confirm-Dialog-plugin