【发布时间】:2013-03-28 23:36:24
【问题描述】:
如果以下 ajax 脚本未返回 1,我将尝试为整个 validator.registercallback 函数返回 true。但是,它不起作用,我认为它可能是我缺少的基本内容,但我想不通。
validator.registerCallback('unique_username', function(value) {
//use ajax to run the check
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(xmlhttp.responseText != 1) {
alert('Username Exists');
return false;
} else {
alert('Username Available!');
return true;
}
}
}
xmlhttp.open("GET","uniqueuser.php?username="+value,true);
xmlhttp.send();
})
奇怪的是以下工作,它只是根据 ajax 脚本的值不起作用:
validator.registerCallback('unique_username', function(value) {
//use ajax to run the check
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(xmlhttp.responseText != 1) {
alert('Username Exists');
return false;
} else {
alert('Username Available!');
return true;
}
}
}
xmlhttp.open("GET","uniqueuser.php?username="+value,true);
xmlhttp.send();
return true;
})
所以基本上,我可以告诉它在主函数中返回 true,但是当我试图让它返回 true 时,只有 ajax 脚本中的值不返回 1,它不起作用。顺便说一句,警报确实有效。所以它得到了正确的值,但它不会返回真或假。
感谢任何帮助!
更新
validator.registerCallback('unique_username', function(value) {
//use ajax to run the check
function ajax_result() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
}
}
xmlhttp.open("GET","uniqueuser.php?username="+value,true);
xmlhttp.send();
}
if(ajax_result() != 1) {
alert('Username Exists');
return false;
} else {
alert('Username Available!');
return true;
}
})
【问题讨论】:
-
搜索“ajax 返回值” asynchronous 位特别重要..另外,考虑使用 AJAX 库(不,我不在乎哪个, 但是由于 你把它标记为 jQuery..)
-
stackoverflow.com/questions/5316697/… - jQuery,但应该显示要点(以及如何编写更简洁的代码)以及如果您想要 同步 行为(糟糕!)请参阅stackoverflow.com/questions/2942544/…跨度>
-
我尝试使用 jquery 版本,但也没有用
-
这是我所获得的最接近的,而且,我仍然不确定我应该看什么
-
如果使用非匿名函数作为第二个参数的validator.registerCallback 会怎样? (你在那儿给出一个函数名)。那是一个你可以从任何地方调用的函数。其中包括已检索网页的处理程序(在我的 jQuery 解决方案中)。
标签: javascript jquery ajax