使用 JQuery AJAX 预过滤器检查响应数据并有条件转发到“错误”事件处理程序
我可能偏离了路线,但我想知道是否可以使用 JQuery prefilter 功能分析 Ajax Success 中的响应数据,并根据返回的 JSON(错误消息)中是否存在某些元素,有条件地转发到我的 ajax
调用中的 error
事件处理程序。
如果这是为页面中的任何 ajax 函数全局设置的,那就太好了。
也许这不是解决这个问题的最佳方法;如果有人有其他想法,请告诉我!
前置过滤器:
//only run prefilter on ajax calls expecting JSON back in response, would this
//be the right way to do this?
$.ajaxPrefilter( "json", function( options, originalOptions, jqXHR ) {
jqXHR.success(function(data, textStatus, jXHR) {
if( hasErrors(data) ) {
//forward to error event handler?
}
});
});
Ajax 调用:
$.ajax({
type: "POST",
data: {
theData: "someData"
},
url: theUrl,
dataType: 'json',
cache: false,
success: function (data, textStatus, jqXHR) {
//do stuff on success
}
error: function ( jqXHR, textStatus, errorThrown ) {
//I want to do this stuff if data contains errors from server
}
});
非常感谢!
I may be way off course, but I was wondering if it's possible to use the JQuery prefilter functionality and analyze the response data in an Ajax Success and conditionally forward to the error
event handler in my ajax
calls based on the existence of certain elements in my returned JSON (error messages).
It would be nice if this was globally set for any ajax function in the page.
Maybe this isn't the best way to go about this; if anyone has an alternative idea, please let me know!
The prefilter:
//only run prefilter on ajax calls expecting JSON back in response, would this
//be the right way to do this?
$.ajaxPrefilter( "json", function( options, originalOptions, jqXHR ) {
jqXHR.success(function(data, textStatus, jXHR) {
if( hasErrors(data) ) {
//forward to error event handler?
}
});
});
Ajax call:
$.ajax({
type: "POST",
data: {
theData: "someData"
},
url: theUrl,
dataType: 'json',
cache: false,
success: function (data, textStatus, jqXHR) {
//do stuff on success
}
error: function ( jqXHR, textStatus, errorThrown ) {
//I want to do this stuff if data contains errors from server
}
});
Thank you so much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我是这样做的:我存储原始的成功函数(特定于每个请求),然后附加另一个回调。如果没有错误,我将调用原始回调:
Here's how I do it: I store the original success function (specific for each request), and then attach another callback. If it didn't have errors, I call the original callback: