Eri*_*rik 1 javascript function
在类似下面的代码的情况下,您将如何访问匿名函数中的变量值?我想返回filterData的bool值(xmlhttp.responseText,thisForm); 这将是主checkAvailable函数的布尔值.提前致谢.
function checkAvailable(thisForm) {
var xmlhttp = httpRequest();
var isValid = true;
var un = document.getElementById('u_username').value;
var email = document.getElementById('u_email').value;
xmlhttp.onreadystatechange = function(isValid) {
if (xmlhttp.readyState == 4) {
//I WANT TO ACCESS THIS isValid VARIABLE FROM MAIN FUNCTION checkAvailable
isValid = filterData(xmlhttp.responseText, thisForm);
}
}
xmlhttp.open("GET","profile_fetch_reg_info.php?do=available&un="+un+"&email="+email+"",true);
xmlhttp.send(null);
return isValid;
}
Run Code Online (Sandbox Code Playgroud)
我现在的方式
function validateRegForm(thisForm) {
var isValid = true;
var warningIcon = "";//for later in case we want to use an icon next to warning msg
checkAvailable(thisForm, function(isValid) { });
if(isValid == false)
window.scroll(0,0);
alert(isValid);
return false;//isValidForm;
}
function checkAvailable(thisForm, resultFunction) {
var xmlhttp = httpRequest();
var un = document.getElementById('u_username').value;
var email = document.getElementById('u_email').value;
xmlhttp.onreadystatechange = function(isValid) {
if(xmlhttp.readyState == 4) {
isValid = filterData(xmlhttp.responseText, thisForm);
resultFunction(isValid);
}
}
xmlhttp.open("GET","profile_fetch_reg_info.php?do=available&un="+un+"&email="+email+"",true);
xmlhttp.send(null);
}
Run Code Online (Sandbox Code Playgroud)
修改checkAvailable函数以获取一个附加参数,该参数是使用结果调用的函数.
function checkAvailable(thisForm, resultFunction) {
..
xmlhttp.onreadystatechange = function(isValid) {
if (xmlhttp.readyState == 4) {
//I WANT TO ACCESS THIS isValid VARIABLE FROM MAIN FUNCTION checkAvailable
isValid = filterData(xmlhttp.responseText, thisForm);
resultFunction(isValid);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,你可以这样称呼它:
checkAvailable(thisForm, function(isValid) {
// Use the isValid value which is the result of the checkAvailable call.
});
Run Code Online (Sandbox Code Playgroud)
编辑 这是对您发布的修改后代码的更改.
function validateRegForm(thisForm) {
var isValid = true;
var warningIcon = "";//for later in case we want to use an icon next to warning msg
checkAvailable(thisForm, function(isValid) {
if(isValid == false)
window.scroll(0,0);
alert(isValid);
}
// WARNING!! This will happen before the result is discovered.
// You'll need to modify the function that called into validateRegForm.
// It should not wait for a return parameter either.
return false;//isValidForm;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1309 次 |
| 最近记录: |