我正在以 JSON 格式从 servlet 返回到 JSP 的查询,如下所示。
String json = new Gson().toJson(map3);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
它是一个有效的 JSON 数据。我在这里复制了“json”对象的值并在 JSONLint 中进行了验证。
我在 JSP 中进行 ajax 调用并从 servlet 返回数据,如下所示。
$.ajax({
url: '<%=request.getContextPath()%>/home',
type: 'POST',
data: {
'action': 'getBugReport',
'dateString':document.getElementById("daterangePicker").value,
'projectName': 'All'
},
complete: function(xhr, status) {
if (status === 'error' || !xhr.responseText) {
console.log(error);
alert(status);
}
else {
console.log('It Works!');
}
},
success: function(responseJSON) {
if(responseJSON!="" && responseJSON.data && responseJSON.data.length && responseJSON.data.length>0) {
console.log("enter here");
}
},
error: function(err){
console.log(err);
}
});
它总是进入错误回调并用 200 打印状态代码。我在 responseText 中获取数据。这是控制台中的错误对象响应。
readyState:4 responseText:“{“1400312_PS-QA”:“21天”,“1399343_fixed”:“6天” setRequestHeader:ƒ(名称,值)状态:ƒ()状态:200
甚至完整:函数正在从上面的代码中打印“它可以工作”。
我搜索了整个堆栈溢出并尝试了 dataType: json,jsonp contentType:applicaiton/json 的所有可能性。
我观察到 1 个奇怪的行为,当我传递 dataType:text 时,它将进入成功函数()但 responseJSON 不是预期的格式。它将打破成功内部的if条件。当我在编写 json 数据时在 servlet 中调试时,它在 jsonlint 中显示了有效的 JSON。
请有人在这里帮忙,我的代码出了什么问题?