如何避免多次AJAX调用?

编程入门 行业动态 更新时间:2024-10-09 19:13:27
本文介绍了如何避免多次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调用?

本文发布于:2023-10-19 17:44:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508290.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:AJAX

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!