【发布时间】: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