1、返回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();
}
}
}
2、通过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();
});
}
}
}
});
3、通过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);
}
}
});
4、防止乱码的处理方法:
jsp页面:charset:utf-8
servlet:utf-8
filter:utf-8
在PrintWriter out = response.getWriter()之前加一句
response.setCharacterEncoding("UTF-8")就可以解决乱码的问题。
但是得记住一定要放在声明PrintWwrite之前。
总之,前台界面,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
您可能感兴趣的文章:
- 详谈表单格式化插件jquery.serializeJSON
- 使用validate.js实现表单数据提交前的验证方法
- jquery ajax 如何向jsp提交表单数据
- Javascript 详解封装from表单数据为json串进行ajax提交
- form表单数据封装成json格式并提交给服务器的实现方法
- 基于JavaScript实现带数据验证和复选框的表单提交
- 深入分析JSON编码格式提交表单数据
- JavaScript动态添加数据到表单并提交的几种方式
- asp.net使用JS+form表单Post和Get方式提交数据
- 浅析JavaScriptSerializer类的序列化与反序列化
- JS多个表单数据提交下的serialize()应用实例分析