如果我使用html表单(而不是ajax),则获取服务器的响应代码或返回值

Get the response code or return value of server if I used the html form (not ajax)

本文关键字:服务器 获取 响应 返回值 代码 ajax html 表单 如果      更新时间:2023-09-26

我的web应用程序使用以下web技术:HTML JS、CSS和appweb服务器。

我正在创建一个登录页面。我当然有一个表单,用户名和密码的值是使用jquerypost发送的。如果用户的用户名和密码正确,服务器端代码会将用户重定向到登录页,比如"/MyPage.html"。如果输入无效,服务器会发送一个json格式的数据,看起来像这样:

{"错误":"无效的用户名或密码"}

这不起作用,因为根据我使用的服务器的支持,"浏览器不会基于301/302到ajax请求进行重定向。"

所以我别无选择,只能使用html提交表单。这是我删除所有css的登录表单。

<form action="/usr/login" method="post">
username: <input type="text" name="username" "><br>
Password: <input type="password" name="password" ><br>
<button>Sign in</button>
</form>

这是那些想看的人的jquery代码。

$.ajax({ 
   url:"/user/login", 
   type:"POST", 
   data: { 
      username : document.getElementById("username").value,     
      password : document.getElementById("password").value  
   }, 
   error:function(xhr, status){     
      if (xhr.status == "401") { 
         document.getElementById("invalid").innerHTML='<div class="alert alert-danger" role="alert">Invalid ID or password.</div>';     
         document.getElementById("password").value = "";    
      }else if (xhr.status == "404") {      
         document.getElementById("invalid").innerHTML='<div class="alert alert-danger" role="alert">Page not found.</div>';     
         document.getElementById("password").value = "";    
      }else{        
         document.getElementById("invalid").innerHTML="";   
      }  
  } 
});

1) 如果不使用ajax,我如何知道(客户端)输入是否无效?2) 考虑到限制,是否可以获得服务器的响应代码?怎样

假设您知道将从服务器获得的确切消息,那么您可以从服务器得到的json字符串中提取它,并进行正常比较来检查它。

   error:function(xhr, status)
         {     
           var json    = xhr.responseText;
           var jsonObj = JSON.parse(json);
           var msg     = jsonObj.error;  
             if (msg == "Invalid username or password") 
             {  
                 // your code to set the innerHTML or javascript to perform redirection
             }
         } 

希望它能有所帮助!