jquery ajax submits data to the backend

Keywords: Javascript JQuery Java JSP

Hello everyone, today brother Tiezhu brings you a piece of jquery ajax to submit data to the back-end teaching.

The front-end data submitted by students who are new to Java Web are basically submitted in form form form, which is not very fun for me anyway. But JavaScript ajax writes a lot, looks headache. jquery ajax is easy to understand and learn.

Don't talk too much. Take a tutorial~

Create a new Web project, and create a new index.jsp under the \ WebContent

 

Don't panic after the new one is created. The default jsp code needs to be changed. I changed it to UTF-8

 

 

 

After that, we will directly import the js file of jquery. Because we have access to the Internet, I don't want to download js directly:

 

 

Direct online path to JS: < script SRC = "https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js" > < script >

Simply and plainly, write two input boxes:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<input type="text" id="userName"/>
<input type="text" id="password"/>
<a onclick="btnConfirm()">Point I submit</a>//Click events
</body>
</html>

In fact, I still want to take a screenshot directly here, but I'm afraid that you will spray me with "what author, only send pictures". But there's really nothing to copy here. There's not much nonsense. Let's go on.

 

After writing here, don't rush to write js. Let's write down how to receive it in the background first. Hahaha, we need to send pictures again

 

 

 

package com.tiezhu.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name="LoginServlet",urlPatterns="/login")
public class LoginServlet extends HttpServlet{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
    }
    
    

}

OK, let's fix the java class. Let's go back to jsp. Come on, keep up with the team~

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<input type="text" id="userName"/>
<input type="text" id="password"/>
<a onclick="btnConfirm()">Point I submit</a>
<script type="text/javascript">

function btnConfirm(){//a Click event in tag
    var userName=$("#userName").val();//adopt id Get the value entered by the user in the input box
    var password=$("#password").val();
     $.ajax({
            type : 'post',
            url : '${pageContext.request.contextPath}/login',
            //There/login Corresponding LoginServlet Annotated in class urlPatterns="/login"
            data:{'userName':userName,'password':password},
            traditional : true,
            async : false,      
           dataType: 'json',
            success : function(data){//Successful events
                alert("Brother Tiezhu is so handsome");
            },
            error : function(data){//Failed events
                alert("You're a loser!");
            }
        });   
}
</script>
</body>
</html>

Now it's basically ok. I don't explain all kinds of actions in ajax one by one. Baidu has a lot of them. In fact, I don't need to know what it means. It's good to get it done.

Now let's go to the LoginServlet class to write the receive

package com.tiezhu.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name="LoginServlet",urlPatterns="/login")
public class LoginServlet extends HttpServlet{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName=req.getParameter("userName");
        String password=req.getParameter("password");
        System.out.println("Data received from the front end: userName="+userName+"password="+password);
    }
    
    

}

There's basically nothing wrong with that. Let's run the project and try it

 

 

 

 

 

 

 

 

 

OK, the back end can receive the value from the front end normally. Why do you say I'm a loser

Because the backend only receives values, but it doesn't tell ajax what's going on. We have to go back to ajax and tell it that everything is OK on our side.

 

 

resp.getWriter().write("666"); return something to the front end at will. As long as you return something, ajax will know that you are still alive.

Run again~

 

 

 

All right. That's it this time. If you don't understand, please discuss in the comment area~

Posted by johnsworld on Thu, 28 Nov 2019 06:51:53 -0800