ajax处理返回的json数据
发布时间:2020-12-16 00:40:46 所属栏目:百科 来源:网络整理
导读: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.fl
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的 $.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 总之,前台界面,java文件,数据库和数据库的连接都有采用统一编码,才不会出现乱码等情况。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |