在網頁上,我使用JQuery向我的servlet發送Ajax調用。Servlet request.getParameter返回null
function sendAjax() {
$.ajax({
url: "/AddOrUpdateServlet",
type: 'POST',
dataType: 'json',
data: {"name": "hello world"},
contentType: 'application/json',
mimeType: 'application/json',
success: function (data) {
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
}
在AddOrUpdateServlet的doPost方法,我有以下代碼:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name = request.getParameter("name");
if (name == null)
System.out.println("null");
/*
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Integer(1).toString());
response.getWriter().close();
*/
}
我可以看到參數已成功由servlet作爲打印「空」控制檯發送和接收。但爲什麼servlet無法獲取「名稱」參數?
爲什麼你設置'mime類型: '應用/ JSON','? – epascarello