我正在使用以下代码通过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调用?
发布评论