JQuery + Ajax - 如何使用重置按钮清除结果部分?

时间:2015-04-17 13:06:08

标签: jquery ajax jsp

我正在学习Jquery并偶然发现了我无法绕过的问题。 在我从互联网上获得的以下示例中,我有JSP表单(简单的加法计算器)和Servlet,它们将两个数字相加并在按下“计算”按钮时返回结果。

我的问题是,在按下“重置”按钮后,我找不到如何清除JSP结果部分的方法。我正在讨论的部分是这样的:<div id="result"></div>在JSP文件的末尾。

JSP:

    <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Ajax Example in JSP And Servlet</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 $('#btn').click(function() {

  var data = $('#xForm').serializeArray();


 $.ajax({
   type:"POST",
   url:"CalcAjax",
   data:data,
   cache: false,
   success:function(msg)
   {
    $("#result").hide();
    $("#result").html("Addition Value is: " + msg + " ").fadeIn("slow");
   }
  });

 });
});
</script>


</head>
<body>
<form id="xForm" method="post" ACTION="/CalcAjax">
 Enter number1:
 <input id="number" type="text" name="number" />
 Enter number2:
 <input id="number1" type="text" name="number1" />
 <input id="btn" type="button" value="Calculate" name="btn"/>&nbsp;&nbsp;
 <input id="reset" type="reset" name="reset" value="Reset"/>
</form>
<div id="result"></div>
</body>
</html>

的Servlet

package com.test;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CalcAjax extends HttpServlet {
private static final long serialVersionUID = 1L;

String redir="";
String urlencode=""; 

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  try { 
            redir=("/ajax.jsp");
            urlencode = response.encodeRedirectURL(redir.toString());
            response.sendRedirect(urlencode);

        } catch (Throwable t) {
            RequestDispatcher dispatcher4 = request.getRequestDispatcher("/ajax.jsp");
            dispatcher4.forward(request, response);
        } 
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
    int number = 0,number1=0;

    number = Integer.parseInt(request.getParameter("number"));
    number1 = Integer.parseInt(request.getParameter("number1"));

    PrintWriter out=response.getWriter();
    out.println(number+number1+" <br>");

 }
}

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:4)

可以使用简单的click()函数完成:

$("#reset").click(function(){
  $("#result").empty();
});

答案 1 :(得分:1)

$("#reset").on("click", function(e) {
    $("#result").empty();
});