Servlet无法读取XMLHttpRequest参数

时间:2018-09-24 21:32:29

标签: javascript java servlets xmlhttprequest

我正在像这样从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

2 个答案:

答案 0 :(得分:0)

您的代码似乎正常,请尝试打印出通过request.getParameterMap();获得的所有参数 您将什么作为参数传递给num变量?我假设它是一个数字,但如果是字符串,则需要确保它也是URL编码

答案 1 :(得分:0)

发现了问题:这是Bij = reshape(Aij,[nA,nA,nB,nB],order=[2,1,4,3]) Lpq = reshape(Bij,[nA*nA,nB*nB]) 行。您的名字是setRequestHeader,应该是application/www-x-form-urlencoded。尝试将以下行替换为您的代码。否则,您的代码会像魅力一样工作(我已经尝试过了)。

application/x-www-form-urlencoded