今天通過ajax請求服務(wù)端數(shù)據(jù)遇到一個問題:無法直接通過
response.attribute方式獲取json response的某個屬性。
打印出請求返回的數(shù)據(jù),發(fā)現(xiàn)返回值并不是一個javascript object,
而是一個json string, 必須JSON.parse之后才能使用。
對比之前寫的ajax請求與springMVC controller發(fā)現(xiàn)問題在于request頭部的Accept與response的content-type。
ajax請求沒有指定dataType, controller沒有指定produces的類型,默認(rèn)accept為任意類型,而response為plain/text,所以接收到的response被理解為字符串。解決方式如下:
設(shè)置ajax dataType為json, 收到請求后會自動parse成object.
spring會根據(jù)請求accept的類型來推斷設(shè)置content-type類型。或設(shè)置@RequestMapping 的produces為"application/json",
jquery會根據(jù)content-type來處理返回值或兩者都設(shè)置