我花了10年时间编写ASP / Ajax并且必须切换到JAVA。 我开始非常简单的脚本,以便在深入了解更复杂的东西之前清楚地理解这些概念。我正在使用Tomcat 7,Servlet 3
问题是。成功调用servlet但不传输表单数据
这是编辑过的servlet(Main.java)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Main
*/
@WebServlet("/Main")
public class Main extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Main() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//int ids;
//String ids;
//response.setContentType("text/html;charset=UTF-8");
//PrintWriter out = response.getWriter();
String val = request.getParameter("id");
String name = request.getParameter("name");
//response.getWriter().write(val);
//response.getWriter().write("::");
//response.getWriter().write(name);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(val +" "+ name);
//System.out.print(val);
//if(val != null){
// //ids = Integer.parseInt(val);
// //out.print(ids);
// out.print(val);
//}
}
}
这是编辑过的JSP(Main.jsp):
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.ajaxSetup({ cache: false });
$(document).ready(function() {
$('#submit').click(function(event) {
var form = (event.target.form),
url = "/Main"
+ "?lName=" + escape(form.elements.lName.text)
+ "&fName=" + escape(form.elements.fName.text);
$.get(url, function(getData) {
$('#somediv').text(getData);
});
});
});
</script>
</head>
<body>
<form id="Main" action="Main" method="post">
<h4>AJAX Demo using Jquery in JSP and Servlet</h4>
Enter your Name:
<br/><input type="text" id="fName" name="fName"/>
<br/><input type="text" id="lName" name="lName"/>
<br/><input type="submit" id="submit" value="Ajax Submit"/>
<br/>
</form>
<div id="somediv">....</div>
</body>
</html>
答案 0 :(得分:1)
编辑:如果未传输表单数据,那是因为您没有将其发送到服务器。 GET请求意味着您需要在网址中附加lName=abc&fName=def
:
<script>
$.ajaxSetup({ cache: false });
$(document).ready(function() {
$('#submit').click(function(event) {
var form = (event.target.form),
url = "/SomeServlet"
+ "?lName=" + escape(form.elements.lName.text)
+ "&fName=" + escape(form.elements.fName.text);
$.get(url, function(getData) {
$('#somediv').text(getData);
});
});
});
</script>