前端Vue採用jsonp方法訪問後臺數據
前端請求代碼:
getAllList() {
//導入Vue-resource.js,通過this.$http發起數據請求
//this.$http.get('url').then(function(result){})
//通過then指定回調函數,可獲取服務器返回的數據
//判斷result.status是否等於200,200爲請求成功。
//若是0,則將result.body賦值給this.list。若不是則提示獲取數據失敗 this.$http.jsonp('http://localhost:8080/VueServer/server')
.then(function(result) {
console.log(result)//便於查看數據返回情況
if(result.status === 200) {
this.list = result.body
} else {
alert('獲取數據失敗')
}
})
}
後臺servlet主要代碼:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("content-type", "text/html;charset=UTF-8");
PrintWriter out;
out=resp.getWriter();
out.write("[{id:1, name:'奔馳'},{id:2, name:'寶馬'}]");
}
在控制檯Network查看,該請求是有數據返回的,但是Response的body或者data爲空,狀態碼status爲0
原因是jsonp在發送請求的時候在URL後面自動添加了 一個callback參數,而而我們沒有把這個參數返回導致Response無數據
解決方法:
在後臺獲取callback的值並將其與返回數據拼接後一起放回
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("content-type", "text/html;charset=UTF-8");
PrintWriter out;
out=resp.getWriter();
//獲取callback值與需要返回的數據拼接,一併返回給前端。注意需要返回的數據需要用小括號“()”包裹起來
out.write(req.getParameter("callback") + "([{id:1, name:'奔馳'},{id:2, name:'寶馬'}])");
}
這樣前端就可以準確獲取數據了,如圖