【问题标题】:Java Servlet request.getParameter is null [duplicate]Java Servlet request.getParameter 为空 [重复]
【发布时间】:2016-11-02 00:58:47
【问题描述】:

我想使用 request.getparameter 来确定我的页面事件的操作。示例添加或删除按钮。

但是当我有按钮时 onsubmit="post();return false;" ajax 的 Javascript 返回内容类型 application/json request.get 参数始终为 null。

当我删除 onsubmit 方法时,我会得到请求参数等于“add”。

在这种情况下,我应该如何确定操作,以便我可以在页面上拥有不同的按钮。

JavaScript
function post() {
    var xhttp;
    if (window.XMLHttpRequest) {
        // code for modern browsers
        xhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xhttp.onreadystatechange = function () {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            document.getElementById("postView").innerHTML = xhttp.responseText;
        }
    };
            //Do someting
    xhttp.open("POST", "myServlet", true);
    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.send(jsonObj);
}

HTML Form
<form name="myForm" action="myServlet" method="post" onsubmit="post();return false;">
Name: <input type="text" id="fnText">
<input type="submit" name="add" value="Add" />
</form>


Java Servlet
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("Method "+request.getMethod());           
String add = request.getParameter("add");
System.out.println("getParameter is " + add);
}

【问题讨论】:

    标签: javascript java json ajax servlets


    【解决方案1】:

    当您通过 ajax 调用(即使用 post() 函数)发送请求时,您并未传递表单的值。

    当您删除 onsubmit 方法时,您正在使用表单的操作,并且表单正在被编码并在 http 请求中发送。

    注意:您应该考虑使用jQuery,这样您的javascript代码将大大简化。

    看到这个帖子:Pass entire form as data in jQuery Ajax function

    【讨论】:

      【解决方案2】:

      你没有设置jsonObj的值,你需要传递它,否则你将不会收到任何值。

      这是您应该发送的示例:

      xmlhttp.open("POST", "/myServlet");
      xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      xmlhttp.send(JSON.stringify({"add":"add"}));
      

      【讨论】:

        猜你喜欢
        • 2019-02-01
        • 2021-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多