페이지의 모든 AJAX 요청에 "후크"추가
모든 단일 AJAX 요청 (전송 될 때 또는 이벤트에 대해)에 "연결"하여 작업을 수행 할 수 있는지 알고 싶습니다. 이 시점에서 페이지에 다른 타사 스크립트가 있다고 가정합니다. 이들 중 일부는 jQuery를 사용하고 다른 일부는 사용하지 않을 수 있습니다. 이게 가능해?
aviv의 대답에 영감을 받아 약간 조사를했는데 이것이 제가 생각 해낸 것입니다. 스크립트의 주석에 따라
유용하다고 는 할 수 없으며 물론 기본 XMLHttpRequest 객체를 사용하는 브라우저에서만 작동합니다 .
가능한 한 네이티브 개체를 사용하므로 자바 스크립트 라이브러리가 사용 중이면 작동한다고 생각합니다.
function addXMLRequestCallback(callback){
var oldSend, i;
if( XMLHttpRequest.callbacks ) {
// we've already overridden send() so just add the callback
XMLHttpRequest.callbacks.push( callback );
} else {
// create a callback queue
XMLHttpRequest.callbacks = [callback];
// store the native send()
oldSend = XMLHttpRequest.prototype.send;
// override the native send()
XMLHttpRequest.prototype.send = function(){
// process the callback queue
// the xhr instance is passed into each callback but seems pretty useless
// you can't tell what its destination is or call abort() without an error
// so only really good for logging that a request has happened
// I could be wrong, I hope so...
// EDIT: I suppose you could override the onreadystatechange handler though
for( i = 0; i < XMLHttpRequest.callbacks.length; i++ ) {
XMLHttpRequest.callbacks[i]( this );
}
// call the native send()
oldSend.apply(this, arguments);
}
}
}
// e.g.
addXMLRequestCallback( function( xhr ) {
console.log( xhr.responseText ); // (an empty string)
});
addXMLRequestCallback( function( xhr ) {
console.dir( xhr ); // have a look if there is anything useful here
});
참고 : 수락 된 답변은 너무 일찍 호출되기 때문에 실제 응답을 생성하지 않습니다.
이 작업을 수행 할 수있는 것입니다 일반적으로 절편 어떤 AJAX 세계적하지 망치 어떤 콜백 등 어쩌면 제 3 자 AJAX 라이브러리에 의해 할당 된 그.
(function() {
var origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
console.log('request started!');
this.addEventListener('load', function() {
console.log('request completed!');
console.log(this.readyState); //will always be 4 (ajax is completed successfully)
console.log(this.responseText); //whatever the response was
});
origOpen.apply(this, arguments);
};
})();
여기에서 addEventListener API로 수행 할 수있는 작업에 대한 문서가 더 있습니다.
(이것은 작동하지 않습니다 <= IE8)
당신이 jQuery를 언급 이후, 나는 JQuery와 이벤트에게 알고있는 .ajaxSetup()
방법을 같은 이벤트 트리거를 포함 세트 글로벌 아약스 옵션 success
, error
그리고 beforeSend
- 당신이 찾고있는 것 같은데 어떤이다.
$.ajaxSetup({
beforeSend: function() {
//do stuff before request fires
}
});
물론이 솔루션을 사용하려는 모든 페이지에서 jQuery 가용성을 확인해야합니다.
There is a trick to do it.
Before all scripts running, take the original XHMHttpReuqest object and save it in a different var. Then override the original XMLHttpRequest and direct all calls to it via your own object.
Psuedo code:
var savd = XMLHttpRequest;
XMLHttpRequest.prototype = function() {
this.init = function() {
}; // your code
etc' etc'
};
I've found a good library on Github that does the job well, you have to include it before any other js files
https://github.com/jpillora/xhook
here is an example that adds an http header to any incoming response
xhook.after(function(request, response) {
response.headers['Foo'] = 'Bar';
});
Using the answer of "meouw" I suggest to use the following solution if you want to see results of request
function addXMLRequestCallback(callback) {
var oldSend, i;
if( XMLHttpRequest.callbacks ) {
// we've already overridden send() so just add the callback
XMLHttpRequest.callbacks.push( callback );
} else {
// create a callback queue
XMLHttpRequest.callbacks = [callback];
// store the native send()
oldSend = XMLHttpRequest.prototype.send;
// override the native send()
XMLHttpRequest.prototype.send = function() {
// call the native send()
oldSend.apply(this, arguments);
this.onreadystatechange = function ( progress ) {
for( i = 0; i < XMLHttpRequest.callbacks.length; i++ ) {
XMLHttpRequest.callbacks[i]( progress );
}
};
}
}
}
addXMLRequestCallback( function( progress ) {
if (typeof progress.srcElement.responseText != 'undefined' && progress.srcElement.responseText != '') {
console.log( progress.srcElement.responseText.length );
}
});
jquery...
<script>
$(document).ajaxSuccess(
function(event, xhr, settings){
alert(xhr.responseText);
}
);
</script>
In addition to meouw's answer, I had to inject code into an iframe which intercepts XHR calls, and used the above answer. However, I had to change
XMLHttpRequest.prototype.send = function(){
To:
XMLHttpRequest.prototype.send = function(arguments)
And I had to change
oldSend.apply(this, arguments);
To:
oldSend.call(this, arguments);
This was necessary to get it working in IE9 with IE8 document mode. If this modification was not made, some call-backs generated by the component framework (Visual WebGUI) did not work. More info at these links:
Without these modifications AJAX postbacks did not terminate.
참고URL : https://stackoverflow.com/questions/5202296/add-a-hook-to-all-ajax-requests-on-a-page
'Programing' 카테고리의 다른 글
DataTable을 Excel로 내보내는 방법 (0) | 2020.08.24 |
---|---|
하위 배열 값으로 PHP 정렬 배열 (0) | 2020.08.24 |
프로그래밍 방식으로 식별 열이있는 SQL 테이블을 확인하는 방법 (0) | 2020.08.24 |
안드로이드 웹뷰 위치 정보 (0) | 2020.08.24 |
SearchView의 OnCloseListener가 작동하지 않습니다. (0) | 2020.08.24 |