在JQuery-ajaxbeforesend中调用一个模态对话框来收集一些信息

Invoking a modal dialog to collect some information in JQuery ajax beforeSend

本文关键字:对话框 信息 模态 JQuery-ajaxbeforesend 调用 一个      更新时间:2023-09-26

我正在使用引导程序和JQuery。我想知道在'$.ajaxbeforeSend'中进行ajax调用之前是否可以调用引导模式对话框?我想在提交表单之前收集用户评论。我的页面上有几个按钮需要这种行为。所以,我想让它更通用。

感谢

我建议使用jQuery的Deferred对象(请参阅http://api.jquery.com/category/deferred-object/)。以下是按钮事件处理程序的伪代码:

$('#theButton').on('click', function() {
    var dfd = $.Deferred();
    // Code to show modal dialog here.
    // Pass dfd to the dialog, and have it call dfd.resolve() 
    // when the user has finished, or dfd.reject() in case the
    // user does not complete the form.
    dfd.done(function() {
        // Ajax call here
    });
});

作为参数传递给dfd.done()的函数只有在有人对Deferred对象调用resolve()方法时才会被调用。

由于javascript中的异步事件模型,您不能推迟beforeSend中发送ajax请求。一旦执行了beforeSend,您必须"延迟"ajax请求的唯一机会就是通过从回调返回false来完全取消它。

因此,虽然您可以跟踪一个状态变量,该变量知道表单是否准备好提交(只要表单还没有准备好,就会从beforeSend返回false),但您最好在创建ajax请求之前先进行这些验证检查。

// why do this
$.ajax('/path', {
    beforeSend: function () {
        if (formIsNotReady()) {
            showModal();
            return false;
        }
    }
});
// when you can do this
if (formIsNotReady()) {
    showModal();
} else {
    $.ajax('/path');
}