다음과 같은 jQuery ajax 함수가 있습니다.
jQuery.ajax({
url : '/blabla',
method : 'post',
data: {
bla : bla
}
}).done(function(data) {
// do lots of stuff
});
.. done 콜백 함수에 전달 된 데이터에 session_timed_out 값이 없는지 확인하는 기능을 추가하고 싶습니다. 위의 기능과 유사한 많은 기능이 있지만 모두 다른 작업을 수행하지만 세션이 먼저 시간 초과되었는지 확인해야합니다. done ()을 확장하는 적절한 방법이 있으므로 처음에 시간 초과를 확인합니까? 나는 이와 같은 것을 시도했지만 실패했습니다.
var myAjax = function(options,callback){
var defaults = {
done: function(data){ //hijack the success handler?
if(check(data)){
callback(data);
}
}
};
jQuery.extend(options,defaults);
return jQuery.ajax(options);
}
이 확장 함수를 사용하면 이전과 같이 작동합니다. 즉, 실제 구현에서 done () 콜백으로 대체되는 것처럼 보이므로 확인이 호출되지 않습니다. 그래서 처음에 세션 타임 아웃을 먼저 확인하도록 done () 함수를 "장식"하거나 확장하는 방법이 있는지 알고 싶습니다. 아니면 모든 ajax 완료에 동일한 세션 검사를 수동으로 추가해야합니까?
이 코드 조각은 jQuery ajax 메서드를 재정의하므로 성공적으로 반환되면 추가 검사를 추가 할 수 있습니다.
(function($) {
var yourCustomCheck = function(ajaxRes) {
// Do whatever you need and return a boolean
};
var oldAjax = $.ajax;
$.ajax = function(opts) {
return $.Deferred(function() {
var _def = this;
oldAjax.call(this, opts).done(function(res) {
console.log("this is done first");
if(yourCustomCheck.call(this, res)) _def.resolve(res);
else _def.reject("timeout");
}).fail(function() {
_def.reject();
});
})
}
})(jQuery);
그 후 $.ajax()
정상적으로 사용할 수 있습니다 ..
$.ajax({
.....
}).done(function(res) {
console.log("ok");
}).fail(function() {
console.log("no ok");
});
다음은 작동 예제가있는 jsfiddle입니다. https://jsfiddle.net/jormaechea/kffyo7qL/1/
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다