Ajax,防止点击多个请求

我试图在用户点击登录或注册按钮时阻止多个请求。 这是我的代码,但它不起作用。 只是第一次工作正常,然后返回false ..

$('#do-login').click(function(e) { e.preventDefault(); if ( $(this).data('requestRunning') ) { return; } $(this).data('requestRunning', true); $.ajax({ type: "POST", url: "/php/auth/login.php", data: $("#login-form").serialize(), success: function(msg) { //stuffs }, complete: function() { $(this).data('requestRunning', false); } }); }); 

有任何想法吗? 谢谢!

问题出在这里:

  complete: function() { $(this).data('requestRunning', false); } 

this不再指向按钮。

 $('#do-login').click(function(e) { var me = $(this); e.preventDefault(); if ( me.data('requestRunning') ) { return; } me.data('requestRunning', true); $.ajax({ type: "POST", url: "/php/auth/login.php", data: $("#login-form").serialize(), success: function(msg) { //stuffs }, complete: function() { me.data('requestRunning', false); } }); }); 

使用on()off() ,这就是他们的用途:

 $('#do-login').on('click', login); function login(e) { e.preventDefault(); var that = $(this); that.off('click'); // remove handler $.ajax({ type: "POST", url: "/php/auth/login.php", data: $("#login-form").serialize() }).done(function(msg) { // do stuff }).always(function() { that.on('click', login); // add handler back after ajax }); }); 

您可以禁用该按钮。

 $(this).prop('disabled', true); 

在您的ajax回调中,上下文( this )从外部函数更改,您可以通过使用$ .ajax中的context属性将其设置为相同

 $.ajax({ type: "POST", url: "/php/auth/login.php", data: $("#login-form").serialize(), context: this, //<----- success: function(msg) { //stuffs }, complete: function() { $(this).data('requestRunning', false); } }); 

或者你可以用$(this).addClass("disabled"); 你按钮或链接,点击后,你可以$(this).removeClass("disabled");

// CSS

 .disabled{ cursor: not-allowed; } 

// JQUERY

 $('#do-login').click(function(e) { e.preventDefault(); $(this).addClass("disabled"); $.ajax({ type: "POST", url: "/php/auth/login.php", data: $("#login-form").serialize(), context: this, success: function(msg) { //do more here $(this).removeClass("disabled"); }, }); }); 

PS如果您使用bootstrap css,则不需要css部分。

我发现这种方法很有用。 我已经将它实现为带有ES6的jQuery的通用函数。

 export default function (button, promise) { const $button = $(button); const semaphore = 'requestRunning'; if ($button.data(semaphore)) return null; $button.data(semaphore, true); return promise().always(() => { $button.data(semaphore, false); }); } 

因为$.ajax()返回一个promise,你只需传入promise,然后函数将处理其余的事务。

粗略地说,这是用法。

 import preventDoubleClick from './preventdoubleclick'; ... button.click(() => { preventDoubleClick(this, () => $.ajax() .done(() => { console.log("success") })); }); 

用于防止整个站点中的多个ajax请求。 例如:如果在其他ajax页面中使用ajax请求,在php循环中使用ajax等,请为您提供多个ajax请求,其中包含一个结果。 我有解决方案:

 Use window.onload = function() { ... } 

代替

 $(document).ready(function(){ ... }); 

在index.php主页面上。 它将阻止所有多重请求。 🙂