如何避免多次AJAX调用? [英] How to avoid multiple AJAX calls?

查看:54
本文介绍了如何避免多次AJAX调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码通过AJAX提交表单:

I'm submitting a form via AJAX using the code below:

$( 'form' ).submit(function(e) {

    $.ajax({
        type: 'POST',
        url: ajax_url,
        dataType: 'json',
        data: {
            'action': 'my_action',
            'str': $( 'form' ).serialize()
        },
        success: function( data ) {
            // Do something here.
        },
        error: function( data ) {
            // Do something here.
        }
    });
    return false;
});

背景

我的PHP处理程序执行各种任务,然后发回响应.然后,我可以在成功或错误函数中使用data进行操作.

My PHP handler carries out various tasks and then sends back a response. I can then do something with data in either of the success or error functions.

我的问题

当用户双击表单的提交"按钮时,将发生两次AJAX调用,这将导致我的PHP处理程序中的代码执行两次.

When a user double clicks on the form's submit button, two AJAX calls take place which causes the code inside my PHP handler to execute twice.

我的问题

如果用户双击提交,如何避免执行两次代码?

How can I avoid my code being executed twice if a user double clicks on submit?

推荐答案

在第一次单击时禁用提交"按钮,然后在AJAX调用返回时重新启用它.

Disable the submit button on the first click and re-enable it, when the AJAX call comes back.

例如:

$( 'form' ).submit(function(e) {
    var $form = $(this);
    $form.find('submit').attr('disabled', true);
    $.ajax({
        type: 'POST',
        url: ajax_url,
        dataType: 'json',
        data: {
            'action': 'my_action',
            'str': $( 'form' ).serialize()
        },
        complete: function() {
            $form.find('submit').removeAttr('disabled');
        },
        success: function( data ) {
            // Do something here.
        },
        error: function( data ) {
            // Do something here.
        }
    });
    return false;
});

这篇关于如何避免多次AJAX调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆