简体   繁体   English

为什么我的浏览器在这里说“未捕获的参考错误”?

[英]Why does my browser say “uncaught referenceerror” here?

I'm just doing some tests in my browser to figure out what's going on - everything seems to be working correctly up until this line: 我只是在浏览器中进行一些测试,以了解发生了什么-直到这一行,一切似乎都可以正常工作:

responseJson = JSON.parse(localReq.responseText); responseJson = JSON.parse(localReq.responseText);

When I evaluate this part: JSON.parse(localReq.responseText); 当我评估这部分时:JSON.parse(localReq.responseText); I get the appropriate value. 我得到适当的价值。 But when I evaluate "responseJson" it gives me an uncaught referenceerror and I can't figure out why. 但是,当我评估“ responseJson”时,它给了我一个未捕获的参考错误,我不知道为什么。

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



}

You need to use an event listener on your AJAX request to handle the response from the server asynchronously via a callback. 您需要在AJAX请求上使用事件侦听器,以通过回调异步处理来自服务器的响应。 By not doing this you are checking for a response code of 200 before the server has responded. 通过不这样做,您正在服务器响应之前检查响应代码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);
}

See this jsFiddle: http://jsfiddle.net/wwsj3r4q/ 看到这个jsFiddle: http : //jsfiddle.net/wwsj3r4q/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM