我正在使用 ajax 创建一个登录函数,但遇到了一个问题:成功函数 (SuccessLogin) 在获得 ajax 响应之前触发。我正在从 Eclipse 中将代码作为 google web 应用程序运行,并且在调试 java 类文件时我可以看到,在调试器捕获类文件中的断点之前,javascript 会针对类的成功响应为 false 发出警报。我现在只编写了几个月的代码,所以我确信这是我的一个愚蠢的小错误。
$(document).ready(function() {
sessionChecker()
// sign in
$('#signInForm').click(function () {
$().button('loading')
var email = $('#user_username').val();
sessionStorage.email = $('#user_username').val();
var password= $('#user_password').val();
var SignInRequest = {
type: "UserLoginRequest",
email: email,
password: password
}
var data= JSON.stringify(SignInRequest);
//disabled all the text fields
$('.text').attr('disabled','true');
//start the ajax
$.ajax({
url: "/resources/user/login",
type: "POST",
data: data,
cache: false,
success: successLogin(data)
});
});
//if submit button is clicked
$('#Register').click(function () {
$().button('loading')
var email = $('#email').val();
if ($('#InputPassword').val()== $('#ConfirmPassword').val()) {
var password= $('input[id=InputPassword]').val();
} else {alert("Passwords do not match");
return ;}
var UserRegistrationRequest = {
type: "UserRegistrationRequest",
email: email,
password: password
}
var data= JSON.stringify(UserRegistrationRequest);
//disabled all the text fields
$('.text').attr('disabled','true');
//start the ajax
$.ajax({
url: "/resources/user/register",
type: "POST",
data: data,
cache: false,
success: function (data) {
if (data.success==true) {
//hide the form
$('form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
} else alert('data.errorReason');
}
});
return false;
});
});
function successLogin (data){
if (data.success) {
sessionStorage.userID= data.userID
var userID = data.userID
sessionChecker(userID);
} else alert(data.errorReason);
}
//session check
function sessionChecker(uid) {
if (sessionStorage.userID!= null){
var userID = sessionStorage.userID
};
if (userID != null){
$('#user').append(userID)
$('#fat-menu_1').fadeOut('slow')
$('#fat-menu_2').append(sessionStorage.email).fadeIn('slow') };
}
最佳答案
成功:成功登录(数据)
函数调用和函数定义之间存在差异:
- 函数定义使用
function
关键字并包含函数体{...}
- 函数调用将括号(参数列表)附加到函数名称并实际调用该函数以返回值
如果您向该属性分配函数调用,它将返回一个值,并且该值将被存储。为了避免这种情况,如果您的函数不带任何参数,您可以使用函数名称,或者如果您的函数确实带参数,请将您的函数调用嵌入到另一个函数的定义中:
- 无参数:
成功:successLogin
- 有参数:
success: function() { successLogin(data); }
关于javascript - 在 java 类响应之前触发 Ajax 成功函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13849875/