【发布时间】:2014-06-10 21:20:29
【问题描述】:
我正在尝试将带有 Ajax(POST) 的 json 对象发送到我的 Servlet, Ajax 好像没有被发送到servlet,意味着doPost 函数dosent 运行。 在发送 Ajax 之后,我如何从中获取数据并打印到控制台。 谢谢。
index.jsp:
<%@ page language="java" contentType="text/html; charset=windows-1255"
pageEncoding="windows-1255"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<title>Insert title here</title>
</head>
<body>
<h2>Welcome please fill in the details, and then click Submit</h2>
<hr/>
<input value="Submit2" type="submit" onclick="submitform()">
<script type="text/javascript">
function submitform() {
alert('sending json');
$.ajax({
type: 'POST',
url: '/MyServlet',
data: JSON.stringify({name:"hod"}),
success: function(msg){
alert('wow' + msg);
}
});
alert('done json');
}
</script>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>WebApp-01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.srk.pkg.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
MyServlet.java:
package com.srk.pkg;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
* Servlet implementation class MyServlet
*/
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public MyServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost");
// get the object and print to console
}
}
【问题讨论】:
-
您的浏览器有一个控制台,用于记录 javascript 执行和 HTTP 请求。检查它以获取更多详细信息。
标签: java jquery ajax json servlets