18910140161

JavaScript-为什么不是'是否让我的responseText在if条件下工作(在其他地方工作)?-堆栈溢出

顺晟科技

2022-10-18 12:22:27

246

下面是我的HTML文件中的JavaScript.我正在使用API创建一个简单的登录功能。API POST请求返回“通过登录”或或";登录失败";.

我的函数3()中的

window.alert(datas),它返回";通过的登录";正在返回"登录通过";,但是IF条件中的任何内容都不起作用。

<代码><;脚本类型=";文本/JavaScript";>;函数myFunction2(){//抓取用户输入的值以发布到APIuid=document.getElementById(' username ').value;pass=document.getElementById(' password ').value;//生成POST请求的URLvar URL=http://127.0.0.1:5000//login/'+uid+'/'+pass.//向API发出POST请求const xhr=new XMLHttpRequest();xhr.open(";post";,URL);xhr.send();  xhr.onreadystatechange=function(){if(xhr.readyState==4&;amp;amp;xhr.status==200){如果(xhr.responseText){const data=xhr.responseText;//POST请求返回的JSON我的函数3(数据);}}}}函数MyFunction3(数据){window.alert(数据);if(datas==";登录通过";){localStorage.setItem(";用户";,uid);console.log(localStorage.getItem(";user";));window.alert(localStorage.getItem(";user";));}}<;/脚本>;

顺晟科技:

这个问题是范围问题:

<代码>函数myFunction2(){//抓取用户输入的值以发布到APIuid=document.getElementById(' username ').value;pass=document.getElementById(' password ').value;//生成POST请求的URLvar URL=http://127.0.0.1:5000//login/'+uid+'/'+pass.//向API发出POST请求const xhr=new XMLHttpRequest();xhr.open(";post";,URL);xhr.send();  xhr.onreadystatechange=function(){if(xhr.readyState==4&;amp;amp;xhr.status==200){如果(xhr.responseText){const data=xhr.responseText;//POST请求返回的JSON我的函数3(数据);}}} //此函数需要在范围内,以使UID有效函数MyFunction3(数据){window.alert(数据);if(datas==";登录通过";){localStorage.setItem(";用户";,uid);console.log(localStorage.getItem(";user";));window.alert(localStorage.getItem(";user";));}}}

尝试将函数myFunction3移到myFunction2中。您的if语句正在工作,问题是uid将等于零,因为它不存在于全局范围中。

您还可以通过在代码顶部的MyFunction2外部的全局范围内声明UID来解决此问题。

<script type="text/javascript">



  function myFunction2(){
    //grab user entered values for posting to API
    uid=document.getElementById('username').value;
    pass=document.getElementById('password').value;

    //Generate url for Post request
    var url='http://127.0.0.1:5000//login/'+uid+'/'+pass
    
   
   //making Post request to API
   const xhr = new XMLHttpRequest();  
   xhr.open("POST", url);  
   xhr.send(); 

  
    xhr.onreadystatechange=function(){
      if(xhr.readyState==4&&xhr.status==200){
        if(xhr.responseText){
           const data = xhr.responseText; //json returned by post request
            myFunction3(data); 
           
        }
      }
    }
  }

  function myFunction3(datas){
        window.alert(datas);
         
        if(datas == "login passed"){
          
          localStorage.setItem("user",uid);
          console.log(localStorage.getItem("user"));
          window.alert(localStorage.getItem("user"));
        }
        
  }


</script>
  • TAG:
相关文章
随机推荐
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航