【问题标题】:Can't find the right way to get parameter value from the HttpRequest:找不到从 HttpRequest 获取参数值的正确方法:
【发布时间】:2013-09-27 13:53:05
【问题描述】:

找不到从HttpRequest获取参数值的正确方法:

这是我的 JQuery 文件:

$(document).ready(function() {
var currBoard;
var currCell;
$(".cell").click(function() {

    Cardboard = $ (this). attr ('name');
    currCell = $(this).attr('id');
    $.get('InGameServlet', function(responseText) {
        $("#"+currCell).text(responseText);

        alert("cell num:" + currCell + " Board: " + currBoard);
    });
});

});

这是我的 Servlet:

@WebServlet(name = "InGameServlet", urlPatterns = {"/InGameServlet"})
public class InGameServlet extends HttpServlet {
   protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    printSign(request.getParameter("currBoard"), request.getParameter("currCell"),     response);
}

在调试模式下,我看到我从请求中得到的值是 NULL!

我做错了什么?

【问题讨论】:

    标签: java jquery html servlets


    【解决方案1】:

    您拨打的是getAttribute(),而不是getParameter()

    请求参数作为请求参数存储在HttpServletRequest中。

    使用

    String value = request.getParameter("your parameter key");
    

    这显然取决于您的请求是否实际包含请求参数。 Here's how you do that with jQuery's get().

    【讨论】:

    • 哦,抱歉,这是我做的测试之一……它们都返回 null。
    【解决方案2】:

    你没有从你的 ajax 请求中传递值

    $(".cell").click(function() {
    
        Cardboard = $ (this). attr ('name');
        currCell = $(this).attr('id');
        $.get('InGameServlet?currBoard="+Cardboard+"currCell="+currCell', function(responseText) {  //passing data as quesry param.
            $("#"+currCell).text(responseText);
    
            alert("cell num:" + currCell + " Board: " + currBoard);
        });
    });
    

    然后在servlet中获取请求参数为

    request.getParameter("currBoard");
    

    原来如此,

    printSign(request.getParameter("currBoard"),request.getParameter("currCell"),response);
    

    【讨论】:

      【解决方案3】:

      您似乎没有在$.get ajax 调用中传递任何参数。 另外参数是通过getParameter()而不是getValue()获取的。

      【讨论】:

        【解决方案4】:

        首先您需要将参数与请求一起发送:

        var data = {
            currBoard: $(this).attr('name'),
            currCell: $(this).attr('id')
        };
        $.get('InGameServlet', data, function (responseText) {
            $("#" + currCell).text(responseText);
        
            alert("cell num:" + currCell + " Board: " + currBoard);
        });
        

        然后使用request.getParameter() 而不是getAttribute() 检索它们

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-02
          • 2017-02-21
          • 2015-04-23
          • 2014-03-27
          • 2020-01-22
          • 1970-01-01
          相关资源
          最近更新 更多