我使用$ .ajaxSetup和JSON的自定义转换器,因此我们可以记录错误并执行其他操作,但我真的希望能够知道响应所针对的ajax请求的请求URL:
示例:
$.ajaxSetup({
converters: { "text json": function(json_string) {
try {
var json = $.parseJSON(json_string);
if (json && json.do_something) {
// do something if a property is found
}
return json;
} catch (e) {
// catch any parseJSON errors & send error to our error reporting
// would like to get the url of the ajax request that this response is for
}
}}
});
由于各种原因,我们正在使用html回调一些ajax调用,并且$ .parseJSON将失败(应该如此),但是能够获取ajax请求所针对的url真的很有用,但是我没有看到一个简单的方法来做这件事。想法?
答案 0 :(得分:1)
决定使用ajaxError()全局catch all,这使您可以访问xhr obj和设置(包含url)
像这样:// let $.parseJSON throw it's error and catch it here, so we can get the url
// and other useful info that we can include in our custom error
$(document).ajaxError(function(e, xhr, settings, err) {
var message = 'url: ' + settings.url + ' ' + err.message;
// push message as part of an error to custom error reporting
});
$.ajaxSetup({
converters: { "text json": function(json_string) {
var json = $.parseJSON(json_string);
if (json && json.do_something) {
// do something if a property is found
}
return json;
}}
});