gpt4 book ai didi

javascript - 在函数和对象之外设置变量

转载 作者:行者123 更新时间:2023-12-02 18:51:06 25 4
gpt4 key购买 nike

我正在尝试设置变量 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,则不应提交表单。我现在有了代码(谢谢甜淀粉 enzyme )

   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 ,则表单永远不会提交。

最佳答案

AJAX 是异步的,因此您需要修改 onreadystatechange() 函数,您可以将 result 传递给另一个函数来处理您的逻辑:

   var checkResult = function(result) {
alert("final value: " + result);
/* handle your result here */
};
...

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));

关于javascript - 在函数和对象之外设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15819795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com