$.ajax,$.get等請求成功,卻不執行function()中的程序,而是進入error回調函數 問題分析

此問題雖小,但前後臺不會報錯,初次遇到一時不易排查,需警惕。
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中的程序

  1. Request URL:

    http://localhost:8086/populationDataShow/getCurrentTimeInfo

  2. Request Method:

    GET

  3. 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' 即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章