好吧,我是jquery的新手。我创建了一个简单的表单,从jsp页面获取两个数字。 A将它们发送到servlet,该servlet添加并返回总和。我的问题是总和是打印在一个新的空白页面上,但没有显示在index.jsp页面中。我认为jquery没有收到回应。我已阅读并尝试了许多答案,但似乎无法解决问题。 另外,如果servlet将任何内容返回给jquery,我该怎么办? index.jsp页面。
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="js/jquery-1.11.2.js"></script>
<script>
var frm = $('#form1');
frm.submit(function(){
$.ajax({
type: frm.attr('method'),
url:frm.attr('action'),
data:frm.serialize(),
dataType:"text",
success:function(data){
console.log("success");
$('#somediv').append('data');
}
});
return false;
});
</script>
</head>
<body>
<h1 align="center"> ajax with jquery simple example</h1>
<br>
<form name = "form1" action="/ajax_to_servelet/AjaxExample" method="GET" id="form1" accept-charset="UTF-8">
number 1 : <input type="text" name = "n1"/><br>
number 2 : <input type= "text" name = "n2"/><br>
<input type="submit" value="calculate"/><br>
<div id="somediv"></div></form>
</body>
Servelet的:
/**
* Servlet implementation class AjaxExample
*/
@WebServlet("/AjaxExample")
public class AjaxExample extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AjaxExample() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8");
try{
int n1 = Integer.parseInt(request.getParameter("n1")) ;
int n2 = Integer.parseInt(request.getParameter("n2")) ;
PrintWriter out = response.getWriter();
out.write(n1+n2+"");
}catch(NumberFormatException e)
{
PrintWriter out = response.getWriter();
out.write("null exception error"+e);
}
// TODO Auto-generated method stub
}
}