gpt4 book ai didi

javascript - Servlet 无法读取 XMLHttpRequest 参数

转载 作者:行者123 更新时间:2023-12-02 10:46:51 24 4
gpt4 key购买 nike

我正在从 JavaScript 创建一个 HTTP POST 请求,如下所示:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<input id="num" type="text" />
<input type="button" id="btn" value="submit" onclick="func()"/>
<script>
function func() {
var num = document.getElementById("num").value;
var request = new XMLHttpRequest();
request.open("POST", "/Servlet/MyServlet", true);
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
... }
};
request.setRequestHeader("Content-Type", "application/www-x-form-urlencoded");
request.send("num=" + num);
}
</script>
</body>
</html>

这是我的 servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
...
int num = Integer.parseInt(request.getParameter("num"));
}

调用servlet,但参数为null

最佳答案

发现问题:是setRequestHeader行。您的是 application/www-x-form-urlencoded ,它应该是 application/x-www-form-urlencoded 。尝试将以下行替换到您的代码中。否则你的代码就像魅力一样工作(我已经尝试过了)。

 request.setRequestHeader("Content-type","application/x-www-form-urlencoded");

关于javascript - Servlet 无法读取 XMLHttpRequest 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52487661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com