[英]Extending jQuery ajax success globally
我正在嘗試創建一個在ajax成功回調之前調用的全局處理程序。 我用我的應用程序做了很多ajax調用,如果是錯誤我返回一個特定的結構,所以我需要在成功運行之前運行一些東西來檢查響應數據,看看它是否包含錯誤代碼,如1 / 0
樣品回復
{"code": "0", "message": "your code is broken"}
要么
{"code": "1", "data": "return some data"}
我無法在開箱即用的jQuery中找到一種方法,查看prefilters,ajaxSetup和其他可用的方法,但是它們並沒有完全解決它,我能想出的賭注是攻擊ajax方法本身一點點:
var oFn = $.ajax;
$.ajax = function(options, a, b, c)
{
if(options.success)
{
var oFn2 = options.success;
options.success = function(response)
{
//check the response code and do some processing
ajaxPostProcess(response);
//if no error run the success function otherwise don't bother
if(response.code > 0) oFn2(response);
}
}
oFn(options, a, b, c);
};
我已經使用了一段時間,它工作正常,但想知道是否有更好的方法來做到這一點,或者我在jQuery文檔中遺漏的東西。
您可以構建自己的AJAX處理程序,而不是使用默認的ajax:
var ns = {};
ns.ajax = function(options,callback){
var defaults = { //set the defaults
success: function(data){ //hijack the success handler
if(check(data)){ //checks
callback(data); //if pass, call the callback
}
}
};
$.extend(options,defaults); //merge passed options to defaults
return $.ajax(options); //send request
}
所以你現在使用的是你的電話,而不是$.ajax
;
ns.ajax({options},function(data){
//do whatever you want with the success data
});
此解決方案使用duck punching技術為每個$.ajax()
調用透明地添加自定義成功處理程序
(function() {
var _oldAjax = $.ajax;
$.ajax = function(options) {
$.extend(options, {
success: function() {
// do your stuff
}
});
return _oldAjax(options);
};
})();
以下是一些建議:
var MADE_UP_JSON_RESPONSE = {
code: 1,
message: 'my company still uses IE6'
};
function ajaxHandler(resp) {
if (resp.code == 0) ajaxSuccess(resp);
if (resp.code == 1) ajaxFail(resp);
}
function ajaxSuccess(data) {
console.log(data);
}
function ajaxFail(data) {
alert('fml...' + data.message);
}
$(function() {
//
// setup with ajaxSuccess() and call ajax as usual
//
$(document).ajaxSuccess(function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
$.post('/echo/json/');
// ----------------------------------------------------
// or
// ----------------------------------------------------
//
// declare the handler right in your ajax call
//
$.post('/echo/json/', function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
});
工作: http : //jsfiddle.net/pF5cb/3/
這是你對ajax方法的調用
function getData(newUrl, newData, callBack) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: newUrl,
data: newData,
dataType: "json",
ajaxSuccess: function () { alert('ajaxSuccess'); },
success: function (response) {
callBack(true, response);
if (callBack == null || callBack == undefined) {
callBack(false, null);
}
},
error: function () {
callBack(false, null);
}
});
}
之后回調成功或方法成功
$(document).ajaxStart(function () {
alert('ajax ajaxStart called');
});
$(document).ajaxSuccess(function () {
alert('ajax gvPerson ajaxSuccess called');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.