mau*_*int 32 javascript ajax jquery
我试图在用户点击登录或注册按钮时阻止多个请求.这是我的代码,但它不起作用.只是第一次工作正常,然后返回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);
}
});
});
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?谢谢!
Fra*_*bot 53
问题出在这里:
complete: function() {
$(this).data('requestRunning', false);
}
Run Code Online (Sandbox Code Playgroud)
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);
}
});
});
Run Code Online (Sandbox Code Playgroud)
ade*_*neo 41
使用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
});
});
Run Code Online (Sandbox Code Playgroud)
在您的 ajax 回调中,上下文 ( this
) 从外部函数更改,您可以使用 $.ajax 中的上下文属性将其设置为相同
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
context: this, //<-----
success: function(msg) {
//stuffs
},
complete: function() {
$(this).data('requestRunning', false);
}
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
68205 次 |
最近记录: |