1 問題描述
明明是后臺開發(fā),卻因為接手了一個前后端完全不分離的jsp+servlet+JDBC的項目而被迫走上了寫前端代碼的不歸路……遇到的問題也是極多。
ajax代碼:
$.ajax({
url: globalServer + "/startlogjupyter",
type:'get',
dataType : "json",
data:{
logname:logname,
taskname:taskname
},
success:function (data) {
var noteForURL = document.getElementById("noteforURL");
noteforURL.innerText = data;
noteforURL.style.display = "block";
//打開窗口
window.open(data, "_blank");
},
error:function (err) {
if(window.console){
console.log(err);
}
}
});
java代碼執(zhí)行完主要邏輯返回一個字符串給前端:
//此處省略一大堆代碼
……
String url = "http://www.baidu.com";
response.setCharacterEncoding("utf-8");
response.setContentType("application/json");
PrintWriter out = response.getWriter();
out.write(url);
out.flush();
out.close();
結(jié)果,F(xiàn)12查看network選項中該接口請求成功,state為200,response為"http://www.baidu.com"。但是此時前端卻無法顯示和跳轉(zhuǎn),console log打印的error信息如下圖所示:

console log打印的error信息
看到是parsererror后,開始懷疑請求和后臺的數(shù)據(jù)類型不一致。
最終定位到問題的原因是前后端的數(shù)據(jù)類型不一致,ajax請求中定義了dataType : "json",而后臺返回的是字符串。
2 解決方案
在后臺代碼中將返回的字符串進(jìn)行json轉(zhuǎn)換,轉(zhuǎn)換成json格式的字符串再返回即可。