ajax - 当您期望空结果时,如何防止从 java 服务器端返回 400 代码?
问题描述
我有一个对服务器端 java servlet 的 ajax 调用,并且 null 响应非常有效。但是,我也收到 400 错误代码。问题是 400 错误填满了我的报告 uri 日志,因此很难找到任何“真正的”错误。有没有办法防止400代码。
ajax 调用是:
$.ajax({
url : 'NewsDispView',
data : {
ssAccountLevel : sessionStorage.getItem('ssAccountLevel'),
ssAccountID : sessionStorage.getItem('ssAccountID'),
ssGroupID: sessionStorage.getItem('ssGroupID'),
ssGroupSection: sessionStorage.getItem('ssGroupSection'),
},
type : 'POST',
cache: false,
})
.fail (function(jqXHR, textStatus, errorThrown) {
// alert(jqXHR.responseText);
if(jqXHR.responseText.includes('No News')){
alert("No news");
}else{
alert("News");
}
var marquee = "<span class='glyphicon glyphicon-forward'>";
marquee += " No notices ";
marquee += "<span class='glyphicon glyphicon-forward'>";
$("#newsMarquee").empty();
$('#newsMarquee').append(marquee);
})
.done(function(responseJson1a){
// JSON response to populate the activities table
dataType: "json";
//alert(JSON.stringify(responseJson1a));
//do stuff
})
servlet 返回是:
if (newsList == null || newsList.isEmpty()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No News.");
} else {
String json = new Gson().toJson(newsList);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
解决方案
您也可以将JSON 格式的错误消息传递给您的 ajax 调用。所以,生成你的 json 然后像下面这样传递它:
if (newsList == null || newsList.isEmpty()) {
String json = new Gson().toJson(yourjson);
} else {
String json = new Gson().toJson(newsList);
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
然后,检查您的 ajax 代码是否响应具有密钥 ie :error
并相应地更改您的 ajax 逻辑。
推荐阅读
- scala - Scala通过拆分填充地图列表
- python - 我正在尝试在多输入模型中结合 LSTM 和 CNN,但出现形状错误
- c++ - 使用受保护和继承时无法访问在类中声明的私有成员
- c# - Xamarin 持久颜色选择器
- security - Flutter 中的 flutter_secure_storage 有多安全?
- c++ - 为什么我的比较运算符没有比较我的点长和双精度值?
- docker - Prometheus 在哪里存储指标数据(在容器中)?
- javascript - 在 Vue JS 中使用搜索过滤器时,有没有办法搜索数组中的对象?
- git - 如何像`push`一样从TortoiseGit执行`git tfs rcheckin`?
- unity3d - 已删除的资产仍显示在构建日志中?