Javascript 从失败的$.ajax请求中获取json对象
我刚刚开始这个网络项目。正在使用Typescript。我在看这个:Javascript 从失败的$.ajax请求中获取json对象,javascript,jquery,typescript,Javascript,Jquery,Typescript,我刚刚开始这个网络项目。正在使用Typescript。我在看这个: $.ajax({ type: method, url: url, xhrFields: { withCredentials: $.support.cors }, crossDomain: $.support.cors, data: data, dataType: (this.options.fa
$.ajax({
type: method,
url: url,
xhrFields: {
withCredentials: $.support.cors
},
crossDomain: $.support.cors,
data: data,
dataType: (this.options.fallbackMethod ? this.options.fallbackMethod : "json")
}).then(
(data, textStatus, jqXHR) => { if (typeof (successCallback) === "function") successCallback(data, textStatus, jqXHR); },
(jqXHR, textStatus, errorThrown) => {
console.log("ajax failed: ");
console.log(errorThrown);
console.log(jqXHR);
console.log(textStatus);
if (typeof (failCallback) === "function") failCallback(jqXHR, textStatus, errorThrown);
}
);
当我们向服务器发出请求时,会调用该函数。当我从服务器收到一个错误的请求时,我在Firebug和Fiddler中看到,服务器正在发回一个JSON对象,其中包含错误代码(例如400)和错误消息(“找不到该资源”)
但我不明白的是,如何取回JSON对象,以便我能够解析它。当我记录所有参数(errorThrown、jqXHR、textStatus)时,似乎没有办法恢复JSON。我只看到responseText属性,它将消息和错误代码捆绑在一个字符串中,而不是JSON对象。在调用此方法之前,我做了一次检查,以确保
数据类型实际上是json。有什么想法吗?提前感谢。服务器返回的错误总是存储在responseText
中,即text
。您只需解析responseText即可:
$.ajax({
type: method,
url: url,
xhrFields: {
withCredentials: $.support.cors
},
crossDomain: $.support.cors,
data: data,
dataType: (this.options.fallbackMethod ? this.options.fallbackMethod : "json")
}).then(
(data, textStatus, jqXHR) => { if (typeof (successCallback) === "function") successCallback(data, textStatus, jqXHR); },
(jqXHR, textStatus, errorThrown) => {
console.log("ajax failed: ");
console.log(errorThrown);
// Parse it:
var json = $.parseJSON(jqXHR.responseText);
console.log(json)
console.log(textStatus);
if (typeof (failCallback) === "function") failCallback(jqXHR, textStatus, errorThrown);
}
);
您应该能够通过jqXHR对象的“responseText”属性获取JSON数据。下面的简短示例是一个ajax请求,它使用“error”事件来执行此操作:
$.ajax({
url: 'http://somewhere...',
data: { somedata: 'somevalue' },
type: 'POST',
error: function (jqXHR, statusText, errorThrown) {
// get the JSON here:
var data = JSON.parse(jqXHR.responseText);
}
});
混乱-通常,从服务器获取数据时出错,不会返回有意义的数据。如果从服务器获取数据时没有错误,但是请求导致了某种错误样式的响应,那么服务器应该发送一个“成功”响应(200),其中包含错误数据,供您在客户端上处理。您是否碰巧控制了此服务器,或者它只是您正在使用的一项服务?请原谅我之前的评论,我已经厌倦了解决您的问题:)从您对responseText的描述中,包含字符串而不是JSON响应,答案可能与此问题相同: