【问题标题】:Sending Data from JS to servlet without using <form>不使用 <form> 将数据从 JS 发送到 servlet
【发布时间】:2021-03-13 20:21:30
【问题描述】:

我正在尝试获取一些动态按钮来将它们的 id 发送到我的 servlet。我想我已经很接近了,但只是不知道如何在后端获取数据。

HTML:(动态生成)

<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);
}

小服务程序:

@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);
    }
}

提前致谢!

编辑:

感谢 Nikos Paraskevopoulos!我的 servlet 代码现在看起来像:

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);

【问题讨论】:

    标签: javascript ajax servlets


    【解决方案1】:

    sendXMLHttpRequest 的数据在请求正文中。使用req.getInputStream() 阅读。这会为您提供ServletInputStream,您可以将其视为标准InputStream

    【讨论】:

    • 感谢您的帮助!我之前确实尝试过输入流,但一定是做错了什么......再次感谢!
    猜你喜欢
    • 2012-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 2013-05-27
    • 2014-07-21
    • 1970-01-01
    相关资源
    最近更新 更多