如何从JavaScript(AJAX请求)发送和捕获参数到Servlet

时间:2014-09-27 09:44:14

标签: java javascript jquery ajax servlets

我创建了InformationServlet,每当我需要一些细节时,我都可以发送它想要的东西(使用AJAX),它会返回给我信息。

我搜索了如何在Ajax上执行此操作并根据: How to send parameter to a servlet using Ajax Call

我用过:url: "InformationServlet?param=numberOfPlayers"

但是在servlet上,请求的属性不包含我发送的参数,所以我想我没有正确地做到这一点:
enter image description here

您可以看到属性大小为零

的Servlet

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            Gson gson = new Gson();
            Engine engine = (Engine)getServletContext().getAttribute("engine");
            String responseJson = "";

            if(request.getAttribute("numberOfPlayers") != null)
            {
                String numberOfPlayers = "";
                numberOfPlayers = gson.toJson(String.valueOf(engine.GetNumOfPlayers()));
                responseJson = numberOfPlayers;
            }

            out.print(responseJson);

        } finally {
            out.close();
        }
    }

JavaScript(AJAX请求):

function getNumberOfPlayersAndPrintSoldiers()
{
      $.ajax({
        url: "InformationServlet?param=numberOfPlayers",
        timeout: 2000,

        error: function() {
            console.log("Failed to send ajax");
        },
        success: function(numberOfPlayers) {
            var r = numberOfPlayers;

        }
    });
}

1 个答案:

答案 0 :(得分:1)

修改

您可能希望使用getParameter而不是getAttribute

此外,请注意参数名称的顺序及其值:

request.getParameter("param");

instad of:

request.getParameter("numberOfPlayers");

因为url表单首先包含参数名称,然后是参数值。例如:

myurl.html?param=17

如果需要更多参数,请使用分隔符&符号

myurl.html?firstName=bob&age=5