此問題雖小,但前後臺不會報錯,初次遇到一時不易排查,需警惕。
demo如下:
js代碼:
請求方式一:
$.ajax({
url: '/populationDataShow/getCurrentTimeInfo',
type: 'get',
dataType: 'json',
success: function (data) {
$('#currentTime').empty().html(data);
}
});
請求方式二:
$.get('/populationDataShow/homeProfileHeadInfo', function (data) {
$('#currentTime').empty().html(data);
}
後臺代碼:
@RequestMapping(value = "/getCurrentTimeInfo", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String getCurrentTimeInfo() {
return DateUtil.getCurrentFullTimeStr() + " " + DateUtil.getDayOfTheWeek();
}
上述請求 請求頭部如下 表明是成功的,但就是不執行function中的程序
-
Request URL:
http://localhost:8086/populationDataShow/getCurrentTimeInfo
-
Request Method:
GET
-
Status Code:
200 OK
經分析知道:當返回值與請求設置的數據類型不一致時,雖然請求能成功,可調用的回調函數卻不是success,而是error。
換如下方式:
$.ajax({
url: '/populationDataShow/getCurrentTimeInfo',
type: 'get',
dataType: 'json',
success: function (data) {
$('#currentTime').empty().html(data);
},
error: function (XMLHttpRequest) {
//後臺返回的是字符串,與請求設定的數據類型json不一致,會執行error回調函數,而不是success
$('#currentTime').empty().html(XMLHttpRequest.responseText);
}
});
解決方案:
將請求設定的數據類型與後臺返回值類型保持一致,本案例 需將dataType: 'json' 修改爲 dataType: 'text' 即可。