我正在尝试获取一些动态按钮,以将其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);
}
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);
}
}
提前致谢!
编辑:
感谢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);
您send
使用的数据XMLHttpRequest
在请求正文中。用阅读req.getInputStream()
。这为您提供了一个ServletInputStream
,您可以将其作为标准阅读InputStream
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句