简体   繁体   English

jQuery等待AJAX​​呼叫完成

[英]Jquery Wait Until AJAX Call is Done

I have an ajax function for saving a forms data. 我有一个用于保存表单数据的ajax函数。 I want it to remain asynchronous because the users can hit save any time. 我希望它保持异步状态,因为用户可以随时点击保存。 However, I have another function that converts the form to a PDF and I want it to run the save function before creating the PDF (in case the users have added more data). 但是,我还有另一个函数可以将表单转换为PDF,并且我希望它在创建PDF之前运行保存功能(以防用户添加了更多数据)。 Is there a way to make $('input.submit') wait for save to finish before opening the pdf? 有没有办法让$('input.submit')等待保存完成后再打开pdf? Below is the jQuery I am using: 以下是我正在使用的jQuery:

$("button#save").on('click', function (){
                $.ajax({
                    type: 'POST',
                    url: '<?php echo matry::base_to('utilities/crm/field_day_save');?>',
                    data: $("form#trip_form").serialize(),
                    dataType: 'json',
                    success: function (data)
                    {
                        $("#alerts").html(data.alert);
                        $("#form_id").val(data.id);
                    }
                    });
            });
        $("input.submit").on('click', function(event){
            event.preventDefault();
            $("button#save").trigger('click');
            window.open('<?php echo matry::base_to('custom_worddocs/field_day');?>' + '&fd_id=' + $("#form_id").val());
        });

In short, I want $('button#save').click() to remain asynchronous, but I want $(input.submit) to wait for button save to complete before opening new window. 简而言之,我希望$('button#save').click()保持异步,但我希望$(input.submit)等待按钮保存完成之后再打开新窗口。

jQuery's ajax function returns a jqXHR object which, among other things, behaves like a deferred . jQuery的ajax函数返回一个jqXHR对象,该对象的行为类似于deferred

By only calling window.open from within the then function, it'll wait for the AJAX to complete: 通过仅从then函数中调用window.open ,它将等待AJAX​​完成:

$("button#save").on('click', function () {

    var jqXHR = $.ajax({ /* your config... */ });

    $("input.submit").one('click', function(event) {
        event.preventDefault();
        $("button#save").trigger('click');

        jqXHR.then(function () {
            window.open('<?php echo matry::base_to('custom_worddocs/field_day');?>' + '&fd_id=' + $("#form_id").val());
        });
    });

}

Have your click handler return a promise object, then use triggerHandler() to trigger the click event and get it's return value. 让您的点击处理程序返回一个triggerHandler()对象,然后使用triggerHandler()来触发click事件并获取其返回值。

$("button#save").on('click', function (){
    return $.ajax({
        ...

and

...
$("button#save").triggerHandler('click').done(function(){
    window.open(...);
});
...

Proof of concept: http://jsfiddle.net/SRzcy/ 概念验证: http//jsfiddle.net/SRzcy/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM