Warm tip: This article is reproduced from serverfault.com, please click

Sending Data from JS to servlet without using <form>

发布于 2020-12-01 21:06:49

I am trying to get some dynamic buttons to send their id to my servlet. I think I am close but just cant figure out how to get the data on the backend.

HTML: (dynamically generated)

<button class="btn btn-success btn-reimb" id="${res[i][1].id}" onclick='approve(this)'><i class="fas fa-check"></i></button>

JS:

const approve = (e) => {
    console.log(e.id);
    const id = e.id;
    var xhttp;
    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState === 4 && this.status === 200) {
           console.log("Sending...")
        }
    };
    xhttp.open("POST", 'approve', true);

    xhttp.send(id);
}

Servlet:

@WebServlet(name = "approve", urlPatterns = {"/approve"} )
public class ApproveServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String id = req.getParameter("id");

        System.out.println(id);
    }
}

Thanks in advance!

EDIT:

Thanks to Nikos Paraskevopoulos! My servlet code now looks like:

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    
ServletInputStream input = req.getInputStream();

        StringBuilder string = new StringBuilder();
        try (Reader reader = new BufferedReader(new InputStreamReader
                (input, Charset.forName(StandardCharsets.UTF_8.name())))) {
            int c = 0;
            while ((c = reader.read()) != -1) {
                string.append((char) c);
            }
        }
        int id = Integer.parseInt(string.toString());


        System.out.println(id);
Questioner
AndreTheTallGuy
Viewed
0
Nikos Paraskevopoulos 2020-12-02 05:46:12

The data you send with XMLHttpRequest is in the request body. Read it with req.getInputStream(). This gives you a ServletInputStream, which you can read as a standard InputStream.