我遇到的问题是我无法访问函数外部变量的值。我刚刚开始学习jQuery而且我非常喜欢它,但这让我已经停留了很长一段时间。
我已经阅读了与此相关的其他线程,但这些方法仍无效!
$.get("/new/verify.php", { username: username, email: email },
function(data){
var stop_loading = '0';
if(data == 'username')
{
alert('username taken');
$('#username_taken_error').show();
$('#username').focus();
stop_loading = '1';
}else if(data == 'email') {
alert('email taken');
$('#email_taken_error').show();
$('#email').focus();
stop_loading = '1';
}else if(data == 'username|email') {
alert('username/email taken');
$('#username_taken_error').show();
$('#email_taken_error').show();
$('#username').focus();
stop_loading = '1';
}
});
alert(stop_loading);
if(stop_loading == '1') {
alert('Stop loading');
return false;
}
答案 0 :(得分:2)
由于$.get()
执行异步的AJAX请求,因此在$.get()
成功函数中,使用stop_loading
调用另一个函数,如下所示:
$.get("/new/verify.php", { username: username, email: email },
function(data){
var stop_loading = '0';
if(data == 'username')
{
alert('username taken');
$('#username_taken_error').show();
$('#username').focus();
stop_loading = '1';
}else if(data == 'email') {
alert('email taken');
$('#email_taken_error').show();
$('#email').focus();
stop_loading = '1';
}else if(data == 'username|email') {
alert('username/email taken');
$('#username_taken_error').show();
$('#email_taken_error').show();
$('#username').focus();
stop_loading = '1';
}
// call function with stop_loading
callAFunction(stop_loading);
});
// this function will be called
// with stop_loading arugment
function callAFunction(stop_loading){
if(stop_loading == '1') {
alert('Stop loading');
return false;
}
}
答案 1 :(得分:1)
在父范围内声明您的变量: var stop_loading ='0';
$.get("/new/verify.php", { username: username, email: email },
function(data){
if(data == 'username')
{
alert('username taken');
$('#username_taken_error').show();
$('#username').focus();
stop_loading = '1';
}else if(data == 'email') {
alert('email taken');
$('#email_taken_error').show();
$('#email').focus();
stop_loading = '1';
}else if(data == 'username|email') {
alert('username/email taken');
$('#username_taken_error').show();
$('#email_taken_error').show();
$('#username').focus();
stop_loading = '1';
}
});
alert(stop_loading);
if(stop_loading == '1') {
alert('Stop loading');
return false;
}