直到今天,才发现JQuery原来有个Form表单插件,而且还是无刷新页面提交表单,看来自己还要多加强学习啊!不多说了,直接贴代码吧,代码比较简单!
Servlet代码:
package com.project.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AjaxFormServlet extends HttpServlet {
public AjaxFormServlet() {super();}
public void destroy() {super.destroy();}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//String param = request.getParameter("txt");
String param1 = request.getParameter("txt1");
String param2 = request.getParameter("txt2");
System.err.println("参数1的值:param1="+param1+",参数2的值:param2="+param2);
response.setContentType("applicationContext/JSON,encoding=utf-8");
response.getWriter().write("{\"msg\":\"Hello Wold\"}");
}
public void init() throws ServletException {}
}
页面代码:
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
">
首页$(document).ready(function(){
var options = {
type:"POST",//请求方式:get或post
dataType:"json",//数据返回类型:xml、json、script
beforeSerialize:function(){
//alert("表单数据序列化前执行的操作!");
//$("#txt2").val("java");//如:改变元素的值
},
//data:{'txt':"JQuery"},//自定义提交的数据
beforeSubmit:function(){
//alert("表单提交前执行的操作!");
//if($("#txt1").val()==""){return false;}//如:验证表单数据是否为空
},
success:function(json){//表单提交成功回调函数
alert("表单操作完成!操作结果:"+json.msg);
},
error:function(err){
alert("表单提交异常!"+err.msg);
}
};
$("#form").ajaxForm(options);
});
好了,到此结束,是不是很Easy!
注:在操作时遇到一个很诡异的情况,就是由于我的浏览器问题,后台总是无法接收到参数,其他人访问正常,所以请采用两种浏览器多试试,以免遇到类似的问题,花费自己不必要的时间!