jQuery AJAX提交Form表单并处理JSON返回数据详解

作者:桌面漫游时间:2026-10-27 23:07:13浏览:625

本文详解如何利用jQuery的serialize()方法将Form表单数据序列化为字符串,并通过AJAX异步提交至后端Servlet。重点讲解后端如何输出JSON字符串,前端如何通过eval解析返回数据,以及动态渲染表格和绑定点击事件的具体实现。同时提供解决中文乱码的关键配置步骤,确保前后端编码统一。

后端返回JSON字符串

首先,后端需要返回JSON格式的字符串。

具体实现代码如下:

/** 将一个字符串输出到浏览器 */
protected void writeJson(String json) {
PrintWriter pw = null;
try {
servletResponse.setContentType("text/plain;charset=UTF-8");
pw = servletResponse.getWriter();
pw.write(json);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (pw != null) {
pw.close();
            }
        }
    }

前端解析JSON对象与DOM操作

其次,在前端通过eval函数将返回的JSON字符串转换为JSON对象。

相关代码如下:

$.ajax({
data:{
"shipmmsi":shipmmsi,
"shipname":shipname
        },
url : "shipbk/findShipMMSIAndName.do",
async : true,
type : "POST",
success : function(data) {
var ships = eval('(' + data + ')');
$("#bindShipmmsiDiv table tbody").html("");
if(ships!=null){
if(ships.length){
$("#bindShipmmsiDiv").show();
var trs="";
for(var i=0;i<ships.length;i++){
trs+="<tr><td>"+ships[i].mmsi+"</td><td>"+ships[i].vesselName+"</td></tr>";
                    }
$("#bindShipmmsiDiv table tbody").append(trs);
//给tr注册点击事件
$("#bindShipmmsiDiv table tbody tr").click(function(){
$(this).addClass('select_tr').siblings().removeClass('select_tr');
                    });
$("#bindShipmmsiDiv table tbody tr").dblclick(function(){
fillShipMMSIAndName(this);
$("#bindShipmmsiDiv").hide();
                    });
                }
            }
        }
    });

Form表单序列化提交与处理

第三,利用jQuery的$("form").serialize()方法可以将Form表单的数据序列化为字符串后提交到后台,从而通过AJAX操作Form表单并处理返回的数据。

具体代码如下:

$.ajax({
url : 'deliveryWarrant/update.do',
data : $('#myform').serialize(),
type : "POST",
success : function(data) {
var res = eval('(' + data + ')');
if (res && res.success == true) {
alert(res.message);
location.href="/godownWarrant/findToDeliveryWarrant.do?godownWarrant.code="+$("#myform input[name=godownWarrant\\.code]").val();
} else {
alert(res.message);
    }
  }
});

防止乱码的配置方法

第四,为防止出现乱码问题,需进行如下处理:

确保JSP页面、Servlet以及Filter均使用utf-8编码。在PrintWriter out = response.getWriter()之前,务必添加一句response.setCharacterEncoding("UTF-8"),即可解决乱码问题。请注意,该语句必须声明在PrintWriter之前。

总之,前台界面、Java文件、数据库以及数据库连接均需采用统一编码,才能避免出现乱码等情况。

PS:关于JSON操作,这里再为大家推荐几款比较实用的JSON在线工具供大家参考使用:

在线JSON代码检验、检验、美化、格式化工具: http://tools.jb51.net/code/json

JSON在线格式化工具: http://tools.jb51.net/code/jsonformat

在线XML/JSON互相转换工具: http://tools.jb51.net/code/xmljson

json代码在线格式化/美化/压缩/编辑/转换工具: http://tools.jb51.net/code/jsoncodeformat

在线json压缩/转义工具:

http://tools.jb51.net/code/json_yasuo_trans

C语言风格/HTML/CSS/json代码格式化美化工具: http://tools.jb51.net/code/ccode_html_css_json

作者最新文章