<html> <head> <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.7.2.js"></script> <title>ajax提交form表单</title> </head> <body> <form id="form1"> <div><input type="text" name="a" value="11111a" id="a" /></div> <div><input type="text" name="b" value="2bbbb" id="b" /></div> <div><input type="hidden" name="c" value="3 ccc" id="c" /></div> <div> <textarea name="d" rows="8" cols="40">4dddd</textarea> </div> <div><select name="e"> <option value="5值是5" selected="selected">5选择框5</option> <option value="6值是6">6选择可值是6</option> <option value="7">7</option> </select></div> <div> <input type="checkBox" name="f" value="我是checkBox" id="f" /> </div> <div> <!-- <input type="submit" name="g" value="Submit" id="g" /> --> </div> </form> <!-- <input type="button" value="测试用ajax提交表单" onclick="ajaxForm()"> --> <input type="button" value="ajax" onclick="ajaxForm()"> </body> </html> <script type="text/javascript"> function ajaxForm(){ //alert($('#form1').serialize());//a=11111a&b=2+name+%3D+b&c=3+name+%3D+c&d=4+name+%3D+d&e=5&f=%E6%88%91%E6%98%AFcheckBox //document.write($('#form1').serialize()); $.ajax({ type:"POST",async:false,//异步请求 默认为true,设置为false的话,suncess之后,才会继续执行 下面的js //data:"name="+123,data:$('#form1').serialize(),// 你的formid url:"${pageContext.request.contextPath}/ajaxFormServlet",success:function(msg){ alert(msg); },error:function(msg){ alert(msg); } }); alert(123); } </script>
ajax的async默认为true,异步请求的意思。
为了测试这个属性才加上的,加上之后的结果就是 服务器端返回来msg之后,才alert(123);
去掉这个属性,会是先alert(123); 再alert(msg);
servlet接收:
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class AjaxForm */ public class AjaxForm extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request,HttpServletResponse response) */ protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { this.doPost(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request,HttpServletResponse response) */ protected void doPost(HttpServletRequest request,IOException { String a = request.getParameter("a"); String b = request.getParameter("b"); String c = request.getParameter("c"); String d = request.getParameter("d"); String e = request.getParameter("e"); String f = request.getParameter("f"); System.out.println("a:"+a+" b:"+b+" c:"+c+" d:"+d+" e:"+e+" f:"+f); response.setContentType("text/html;charset=utf-8"); //response.getWriter().print("获取成功"); PrintWriter pw = null; try { pw = response.getWriter(); //pw.print("获取到的值处理完成,并返回"); pw.write("获取到的值处理完成,并返回"); } catch (Exception e1) { e1.printStackTrace(); }finally{ if(pw != null){ pw.close(); } } } }