gpt4 book ai didi

javascript - 为什么我的浏览器在这里显示 "uncaught referenceerror"?

转载 作者:行者123 更新时间:2023-12-03 08:28:12 25 4
gpt4 key购买 nike

我只是在浏览器中进行一些测试,以了解发生了什么 - 直到这一行为止,一切似乎都正常工作:

responseJson = JSON.parse(localReq.responseText);

当我评估这部分时: JSON.parse(localReq.responseText);我得到了适当的值。但是当我评估“responseJson”时,它给了我一个 Uncaught ReferenceError ,我不明白为什么。

function login()
{
userName = document.getElementById("_name").value;
password = document.getElementById("_password").value;
data = "userName=" + userName + "&" + "password=" + password;
localReq = new XMLHttpRequest();

localReq.open("POST", "http://universe.tc.uvu.edu/cs2550/assignments/PasswordCheck/check.php", true);
localReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
localReq.send(data);
response = document.getElementById("_login");

if (localReq.status == 200)
{
responseJson = JSON.parse(localReq.responseText);
}



}

最佳答案

您需要在 AJAX 请求上使用事件监听器,通过回调异步处理来自服务器的响应。如果不这样做,您将在服务器响应之前检查响应代码 200

function login(){
userName = "username";
password = "password";
data = "userName=" + userName + "&" + "password=" + password;
localReq = new XMLHttpRequest();

// use an event handler here
localReq.addEventListener("load", function(evt){
if (localReq.status == 200) {
responseJson = JSON.parse(localReq.responseText);
alert("Success: " + localReq.responseText);
} else {
alert("Not Success!= :(");
console.log(localReq);
}
});

localReq.open("POST", "http://universe.tc.uvu.edu/cs2550/assignments/PasswordCheck/check.php", true);
localReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
localReq.send(data);
}

查看这个jsFiddle:http://jsfiddle.net/wwsj3r4q/

关于javascript - 为什么我的浏览器在这里显示 "uncaught referenceerror"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33459493/

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