Jquery ajax 提交表單Demo

用jquery的ajax 異步提交表單數據demo,

導入相關的兩個jquery的js包。

 

index.html

[html] view plaincopy
  1. <html>  
  2. <head>  
  3.     <script type ="text/javascript" src="jquery.js"></script>  
  4.     <script type ="text/javascript" src="jquery.form.js"></script>  
  5. </head>  
  6. <body>  
  7. <script>     
  8.     $(function() {      
  9.         $("input[type='button']").bind("click", function() {    
  10.   
  11.             $.ajax({  
  12.                 type : 'post',  
  13.                 url : 'servlet/ServletDemo',  
  14.                 dataType : 'text',  
  15.                 data : $('#f1').serialize(),  
  16.                 success : function (xmlq) {  
  17.                     alert(xmlq);  
  18.                 },  
  19.                 error : function (xmlq, errq) {  
  20.                     alert(errq);  
  21.                 }  
  22.             });  
  23.               
  24.          });   
  25.     });    
  26.   
  27.         
  28. </script>     
  29.   
  30. <form name="f1" id="f1" action="/servlet/ServletDemo">  
  31.     <input type="text" name="username"/>  
  32.     <input type="text" name="age"/>  
  33.     <input type="button" value="Ajax請求" />    
  34. </form>  
  35.   
  36. </body>  
  37. </html>  


 

ServletDemo.java(Servlet)

[html] view plaincopy
  1. public void doPost(HttpServletRequest request, HttpServletResponse response)  
  2.             throws ServletException, IOException {  
  3.         PrintWriter out = response.getWriter();  
  4.         out.println(request.getParameter("username"));  
  5.         out.println(request.getParameter("age"));  
  6.         out.flush();  
  7.         out.close();  
  8.     }  


 

web.xml

[html] view plaincopy
  1. <servlet>  
  2.    <description>This is the description of my J2EE component</description>  
  3.    <display-name>This is the display name of my J2EE component</display-name>  
  4.    <servlet-name>ServletDemo</servlet-name>  
  5.    <servlet-class>com.xiami.demo.servlet.ServletDemo</servlet-class>  
  6.  </servlet>  
  7.  <servlet-mapping>  
  8.    <servlet-name>ServletDemo</servlet-name>  
  9.    <url-pattern>/servlet/ServletDemo</url-pattern>  
  10.  </servlet-mapping>  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章