Javascript Ajax成功函数在java类响应之前触发
我正在用ajax创建一个登录函数,遇到了一个问题,成功函数SuccessLogin在得到ajax响应之前启动。我以eclipse中的GoogleWeb应用程序的形式运行代码,在调试java类文件时,我可以看到javascript在调试器捕获类文件中的断点之前发出了一个警报,提示类的成功响应为false。我现在只写了几个月的代码,所以我确信这是我犯的一个愚蠢的小错误Javascript Ajax成功函数在java类响应之前触发,javascript,jquery,ajax,twitter-bootstrap,Javascript,Jquery,Ajax,Twitter Bootstrap,我正在用ajax创建一个登录函数,遇到了一个问题,成功函数SuccessLogin在得到ajax响应之前启动。我以eclipse中的GoogleWeb应用程序的形式运行代码,在调试java类文件时,我可以看到javascript在调试器捕获类文件中的断点之前发出了一个警报,提示类的成功响应为false。我现在只写了几个月的代码,所以我确信这是我犯的一个愚蠢的小错误 $(document).ready(function() { sessionChecker() // s
$(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') };
}
您需要将成功封装在匿名函数中,以便它在AJAX调用的范围内执行,而不是立即内联执行:
success: function() { successLogin(data) }
成功:successLogindata
函数调用和函数定义之间有区别:
函数定义使用函数关键字并包含函数体{…}
函数调用将圆括号参数列表附加到函数名,并实际调用函数以返回值
如果将函数调用分配给属性,它将返回一个值,该值将被存储。为了避免这种情况,如果您的函数不接受任何参数,您可以使用函数名,或者如果您的函数确实接受参数,请将您的函数调用嵌入到另一个函数的定义中:
无参数:success:successLogin
Has参数:success:function{successLogindata;}
如果成功函数正在启动,那么它将得到一个ajax响应。。它可能没有利用你在其中有断点的类。也许您应该从servlet开始在调试中遍历代码