我正在尝试设置变量result
,但它仍未定义。
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)
{
result = true
alert(xmlhttp.responseText+" here1")
}
else
{
document.getElementById("report").innerHTML = "wrong password/username"
alert(xmlhttp.responseText+" here2")
result = false
}
}
}
xmlhttp.open("POST", "process.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name="+encodeURIComponent(name.value));
alert("final value: "+result)
return result//always undefined
如何让对象影响它所在函数之外的变量?这个问题比我说的要复杂一些。当用户尝试提交表单时调用此函数。如果返回 true,则应提交表单,如果返回 false,则不应提交表单。我现在有了代码(感谢甜淀粉酶)
var result
var checkResult = function(result) {
alert("final value: " + result);
return result
};
xmlhttp.onreadystatechange=function()
{
var result = null;
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if(xmlhttp.responseText)
{
result = true
alert(xmlhttp.responseText+" here1")
}
else
{
document.getElementById("report").innerHTML = "wrong password/username"
alert(xmlhttp.responseText+" here2")
result = false
}
checkResult(result); // pass result to another function
}
}
xmlhttp.open("POST", "process.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name="+encodeURIComponent(name.value));
但是表单总是被提交,甚至在“最终值...”显示之前。如果我在代码末尾添加 return false 则永远不会提交表单。