js笔记 $.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' 即可。

 

还有一个类似的案列如下:

js 代码片段:

$.ajaxFileUpload({
            url: '/wx/backEnd/tmpMessageController/upload',
            type: 'post',
            data: {"fileName": fileName},
            secureuri: false,
            fileElementId: 'uploadFile',
            dataType: 'json',
            success: function (data) {
                var result = data.data;
                //关闭加载
                layer.close(index);
                if (result.status == "ERROR") {
                    $("#uploadFile").html("").append('<input type="file" id="btnFile" class="btnFile  w-80" name="btnFile">');
                    layer.msg("文件上传失败", {time: 2000}, function () {
                    });

                    return;
                }
            }, error: function (data) {

                /*layer.msg("上传失败,请检查网络及文件大小", {time: 2000}, function () {
                });
*/
                //关闭加载
                layer.close(index);
                return;
            }
        });

 

后端代码片段如下:

@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")

上述请求虽然成功,但是前端一直进入error回调函数,前端出现 Status Code: 406 Not Acceptable。也是因为前后端 返回的数据类型不一致引起的。

解决方式: 后端 produces = "text/html;charset=UTF-8" 改为 produces = "text/json;charset=UTF-8" 。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值