[native JS][POST] request and response (I)
Although the efficiency is a little low, as a beginner, you can look at this first, then look at it, and deal with it with Jason later.
XMLHttpRequest introduction
The XMLHttpRequest object is used to exchange data with the server in the background.
characteristic
- Update the web page without reloading the page
- Request data from the server after the page has been loaded
- Receive data from the server after the page has been loaded
- Send data to the server in the background
XMLHttpRequest uses
Create XMLHttpRequest object
xmlhttp=new XMLHttpRequest();
Older versions of Internet Explorer (IE5 and IE6) use ActiveX objects:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
Establish connection
xmlhttp.open(Submission method,Target page,Is it asynchronous,[Optional parameters]user name,[Optional parameters]password)
xmlhttp.open(method, url, async, username, password);
xmlhttp.open("post","/Login",true)
The first parameter [method]: HTTP request method. It must be a parameter. The values include POST, GET and HEAD. It is case insensitive.
The second parameter [url]: the URL string of the request, which must be a parameter. Most browsers only support homologous requests.
The third parameter [async]: Specifies whether the request is asynchronous. The default value is true. If false, the callback function specified by the onreadystatechange property will be called immediately when the state changes.
The fourth parameter [username]: optional. If the server needs authentication, this parameter specifies the user name. If it is not specified, the authentication window will pop up when the server needs authentication.
The fifth parameter [password]: optional parameter, the password part in the authentication information. If the user name is empty, this value will be ignored.
Set request header
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
POST must be set
Send request (Post)
let name = document.forms['LoginForm']['username'].value; let pwd = document.forms['LoginForm']['userpwd'].value; let params="username="+encodeURIComponent(name)+"&userpwd="+encodeURIComponent(pwd);
xmlhttp.send(params);
1. You can also use var instead of let
2. Use encodeURIComponent() to avoid Chinese garbled code during parameter transmission
3. If the get method is used, the parameters are written in the url and then xmlhttp send(null)
example
<input name="submit" type="button" id="submit" value="Make a request to the server" /> <script> window.onload = function () { //Page initialization var b = document.getElementsByTagName("input")[0]; b.onclick = function () { var url = "server.php?callback=functionName"; //Set query string var xhr = createXHR(); //Instantiate XMLHttpRequest object xhr.open("GET", url, false); //Establish a connection and require a synchronous response xhr.send(null); //Send request console.log(xhr.responseText); //receive data } } </script>
response
xmlhttp.onreadystatechange = function () { if(xmlhttp.readyState===4) alert(xmlhttp.responseText); }
Execute when the status code changes
If readyState equals 4
A pop-up window will pop up with the response text displayed
Servlet
request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String name = request.getParameter("username"); String pwd = request.getParameter("userpwd"); response.getWriter().write(Duser.userLoginCheck(name,pwd)+"");
response.getWriter().write() text, using xmlhttp. XML in js ResponseText receive
An example written by menglang Lantian
front end
<!--Form--> <form name="LoginForm" class="box_info" id="LoginForm" method="post" enctype="application/x-www-form-urlencoded" action="${pageContext.request.contextPath}/Login"> <!--Profile--> <div class="box_profile"> <img src="res/img/pic.jpg" class="set_profile" alt="Profile"/> </div> <div class="box_name"> <label for="username">User Email </label> | <span class="wrong1"></span><br/> <input type="text" name="username" id="username"> </div> <div class="box_pwd"> <label for="userpwd">Password </label> | <span class="wrong2"></span><br/> <input type="password" name="userpwd" id="userpwd"> </div> <div class="box_btn"> <!-- <button id="btn_login" onclick="formCheck()" >Login</button>--> <input type="button" id="btn_login" onclick="formCheck()" value="Login" /> </div> <div class="box_other"> <span class="register"> <a href="register.jsp">Register</a> </span> <span class="forget"> <a href="#">Forget Password</a> </span> </div> <br/> <div align="center"> <div style="display:inline-block;margin:10px;width: 10px;height: 10px;background: #0981f6" onclick="colorSet_Blue()"></div> <div style="display:inline-block;margin:10px;width: 10px;height: 10px;background: #d9212b" onclick="colorSet_Red()"></div> <div style="display:inline-block;margin:10px;width: 10px;height: 10px;background:#23A393" onclick="colorSet_Green()"></div> </div> </form>
If you like this front-end style, you can visit the following blog to learn about it, and then go to gitee to download it
[Web front end] [open source sharing] H5 login interface - December 24, 2021
JS
// For login function formCheck() { let name = document.forms['LoginForm']['username'].value; let pwd = document.forms['LoginForm']['userpwd'].value; let params="username="+encodeURIComponent(name)+"&userpwd="+encodeURIComponent(pwd); if(name==null || name ===""){ document.getElementsByClassName('wrong1')[0].innerHTML="enter one user name"; }else{ document.getElementsByClassName('wrong1')[0].innerHTML=""; if(pwd==null || pwd ===""){ document.getElementsByClassName('wrong2')[0].innerHTML="Please input a password"; }else{ document.getElementsByClassName('wrong2')[0].innerHTML=""; //Submit data var myrequest = new XMLHttpRequest(); myrequest.open("post","/Login",true) myrequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); myrequest.send(params); myrequest.onreadystatechange = function () { if(myrequest.readyState===4) alert(myrequest.responseText); } } } }
Servlet
@WebServlet(name = "Login", value = "/Login") public class Login extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("VCVxWorks"); request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String name = request.getParameter("username"); String pwd = request.getParameter("userpwd"); response.getWriter().write(Duser.userLoginCheck(name,pwd)+""); } }
Existing problems
The response was too slow. The front desk waited a long time to display the results. The teacher suggested that I use Jason for data transmission. See you in our next blog.
References
C language Chinese network - JS XMLHttpRequest introductory tutorial