此问题虽小,但前后台不会报错,初次遇到一时不易排查,需警惕。
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' 即可。
还有一个类似的案列如下:
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" 。