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.VeVB.COm/code/json
JSON在線格式化工具:
http://tools.VeVB.COm/code/jsonformat
在線XML/JSON互相轉換工具:
http://tools.VeVB.COm/code/xmljson
json代碼在線格式化/美化/壓縮/編輯/轉換工具:
http://tools.VeVB.COm/code/jsoncodeformat
在線json壓縮/轉義工具:
http://tools.VeVB.COm/code/json_yasuo_trans
C語言風格/HTML/CSS/json代碼格式化美化工具:
http://tools.VeVB.COm/code/ccode_html_css_json