【问题标题】:Java Ajax request parameters have null valueJava Ajax 请求参数有空值
【发布时间】:2015-06-15 04:54:16
【问题描述】:

我正在尝试使用 Java (JSP + Servlet) 和 Ajax (jQuery) 发出一个简单的 ajax 请求。 Ajax 请求按预期工作,并且到达了 servlet 代码。

问题是我无法获取请求发送的参数值。我得到空值。

这是servlet中的代码:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    response.setContentType("application/json");

    String perfilId = request.getParameter("perfilId"); //Null value
    String perfilNombre = request.getParameter("perfilNombre");  //Null value


    try (PrintWriter out = response.getWriter()) {
        Gson gson = new Gson(); 
        JsonObject obj = new JsonObject();
        obj.addProperty("mensaje", "Algún mensaje. Id: " + perfilId + ", Nombre: " + perfilNombre);

        out.print(gson.toJson(obj));
        out.flush();
    }
}

JSP 中的 Ajax 请求:

$.ajax({
    type: "POST",
    url: 'srvl_def',
    cache: false,
    contentType: "application/json;",
    dataType: "json",
    data: {
        perfilId: $('#perfilId').val(),
        perfilNombre: $('#perfilNombre').val()
    }, 
    success: function (data) {
        alert(data.mensaje);

    }
});

请求数据如下所示:

perfilId=1&perfilNombre=nuevo

也许我错过了什么?

编辑

这是 HTML

    <input type="text" id="perfilId" />
    <input type="text" id="perfilNombre" />

    <button type="button" id="btnGuardar">Enviar</button>

    <script src="js/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
        $('#btnGuardar').click(function (){
            //ajax call
        });
    </script>

【问题讨论】:

  • 尝试将其传递为'perfilId': $('#perfilId').val()。添加引号。或使用JSON.stringify(..)
  • @ShaunakD 我已经尝试过使用 JSON.Stringify,只是尝试使用引号。我仍然得到空值。
  • 请粘贴 HTML...
  • @DarkHorse HTML 已粘贴。

标签: java jquery ajax servlets netbeans


【解决方案1】:

this answer 之后,@ShaunakD 在评论中引用了这个(见问题),我能够获得 ajax 调用发送的值。

调用如下所示:

var perfilId = $('#perfilId').val();
var perfilNombre =  $('#perfilNombre').val();

$.ajax({
    type: "POST",
    url: 'srvl_def',
    cache: false,
    contentType: "application/x-www-form-urlencoded; charset=UTF-8;",
    dataType: "json",
    data: {
        perfilId: perfilId,
        perfilNombre: perfilNombre
    },
    success: function (data) {
        alert(data.mensaje);
    }
});

【讨论】:

  • 我在发出 POST 请求时遇到了同样的问题,发现删除 contentType 参数可以让 servlet 正确传递和读取非空请求参数。
【解决方案2】:

如果你的 ajax 调用在某个函数中,试试这个:

var perfilId = $('#perfilId').val();
var perfilNombre =  $('#perfilNombre').val();
$.ajax({
    type: "POST",
    url: 'srvl_def',
    cache: false,
    contentType: "application/json;",
    dataType: "json",
    data: {
        perfilId: perfilId ,
        perfilNombre: perfilNombre
    }, 
    success: function (data) {
        alert(data.mensaje);

    }
});

【讨论】:

  • 我刚刚测试了这个,我仍然得到空值。
  • 你能粘贴HTML吗...这将有助于解决:)
猜你喜欢
  • 1970-01-01
  • 2017-02-13
  • 1970-01-01
  • 1970-01-01
  • 2014-06-16
  • 1970-01-01
  • 1970-01-01
  • 2012-01-01
  • 1970-01-01
相关资源
最近更新 更多