program tip

JavaScript가 AJAX 이벤트를 감지합니다.

radiobox 2020. 10. 30. 07:52
반응형

JavaScript가 AJAX 이벤트를 감지합니다.


좋아, 그래서 기본적으로 나는 페이지에 약간의 자바 스크립트를 갖고 싶다. 어떻게 든 ajax 요청이 이루어지면 (호출에서 직접 호출하지 않고) 무언가를 감지하고 수행 할 수있는 일종의 글로벌 이벤트 리스너를 첨부하는 방법에 관계없이 ajax 전화가 걸립니다.

ajax 요청이 jquery에 의해 수행 되는 경우 jquery로 이것을 수행하는 방법을 알아 냈습니다 . 이에 대한 예제 코드는 다음과 같습니다.

$.post(
  // requested script
  'someScript.php', 
  // data to send
  {
    'foo' : 'bar',
    'a' : 'b'
  },
  // receive response
  function(response){
    // do something
  }
); // .post

// global event listener    
$(document).ajaxSend(
  function(event,request,settings){
    alert(settings.url); // output: "someScript.php"
    alert(settings.data); // output: "foo=bar&a=b"
  }
);

이 코드를 사용하면 $ .post (..)를 호출하는 위치 / 방법에 관계없이 전역 이벤트 리스너가 트리거됩니다. $ .get 또는 $ .ajax (모든 jquery ajax 메서드)를 사용하는 경우에도 작동합니다. 호출 방법 /시기에 관계없이 (페이지로드시 onclick으로 첨부)

그러나 어떤 js 프레임 워크가 사용되는지 또는 프레임 워크가 사용되지 않더라도 트리거하도록이 리스너를 확장 할 수 있기를 원합니다. 그래서한다면 예를 들어 한 페이지에 (W3 스쿨에서 일반적인 Ajax 코드) 다음 코드를 :

function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","test.txt",true);
xmlhttp.send();
}

그리고 그 함수에 onclick을 호출, 내 글로벌 아약스 이벤트 리스너가 할 수 있어야 어떤 임의의 링크를 가지고 이 요청을 감지합니다. 이 코드를 내 페이지에 추가하고 임의 링크의 onclick (예, 코드 자체가 작동 함)에 첨부했지만 위의 jquery "global event listener"코드는 해당 호출을 감지하지 못했습니다.

좀 더 파헤 쳤고 기본적으로 개체를 임시 개체에 저장하고 지정된 함수를 호출 한 다음 임시 함수를 호출하는 "래퍼"개체로 현재 개체를 덮어 쓸 수 있다는 것을 알고 있습니다. 원래 객체가 생성 / 사용되는 시간. 하지만 항상 미리 알지는 못합니다 ...

그래서 .. 가능할까요? 일반 객체 또는 xyz 프레임 워크에서 수행되었는지 여부에 관계없이 ajax get / post 요청이 만들어 졌음을 감지하는 방법이 있습니까? 아니면 각 프레임 워크를 처리하기 위해 중복 코드를 만들고 미리 생성 / 사용되는 ajax 객체를 알아야합니까?

편집하다:

요청이 발생했음을 감지하는 것만으로는 충분하지 않다는 것을 언급하는 것을 잊었습니다. 또한 요청에서 전송되는 데이터를 캡처해야합니다. 아래 설명에 제공된 링크는 "a"요청이 이루어 졌는지 확인하는 데 도움이되지만 데이터는 전송되지 않습니다. 추신-아래 링크에 제공된 답변은 적어도 어쨌든 나에게는 명확하지 않습니다.


좋아 이것은 내가 지금까지 생각 해낸 것입니다.

<script type='text/javascript'>
var s_ajaxListener = new Object();
s_ajaxListener.tempOpen = XMLHttpRequest.prototype.open;
s_ajaxListener.tempSend = XMLHttpRequest.prototype.send;
s_ajaxListener.callback = function () {
  // this.method :the ajax method used
  // this.url    :the url of the requested script (including query string, if any) (urlencoded) 
  // this.data   :the data sent, if any ex: foo=bar&a=b (urlencoded)
}

XMLHttpRequest.prototype.open = function(a,b) {
  if (!a) var a='';
  if (!b) var b='';
  s_ajaxListener.tempOpen.apply(this, arguments);
  s_ajaxListener.method = a;  
  s_ajaxListener.url = b;
  if (a.toLowerCase() == 'get') {
    s_ajaxListener.data = b.split('?');
    s_ajaxListener.data = s_ajaxListener.data[1];
  }
}

XMLHttpRequest.prototype.send = function(a,b) {
  if (!a) var a='';
  if (!b) var b='';
  s_ajaxListener.tempSend.apply(this, arguments);
  if(s_ajaxListener.method.toLowerCase() == 'post')s_ajaxListener.data = a;
  s_ajaxListener.callback();
}
</script>

지도:

이것을 페이지에 c / p하거나 .js 파일 등에 포함하십시오. 그러면 s_ajaxListener라는 객체가 생성됩니다. AJAX GET 또는 POST 요청이있을 때마다 s_ajaxListener.callback ()이 호출되고 다음 속성을 사용할 수 있습니다.

s_ajaxListener.method : The ajax method used. This should be either GET or POST. NOTE: the value may not always be uppercase, it depends on how the specific request was coded. I'm debating the wisdom of automatically upper-casing it or leaving it to something else to toLowerCase() for a case-insensitive comparison.

s_ajaxListener.url : The url of the requested script (including query string, if any) (urlencoded). I have noticed, depending on how the data is sent and from which browser/framework, for example this value could end up being as " " or "+" or "%20". I am debating the wisdom of decoding it here or leave it to something else.

s_ajaxListener.data : the data sent, if any ex: foo=bar&a=b (same 'issue' as .url with it being url-encoded)

NOTES:

As it stands, this is not IE6 compatible. this solution is not quite good enough for me, as I want it to be IE6 compatible. But since a lot of other people don't care about IE6, I decided to post my solution in its current state, as it should work for you if you don't care about IE6.

I have tested this in (as of this posted date): Current Safari, Current Chrome, Current FireFox, IE8, IE8 (IE7 Compatible). It doesn't currently work with IE6 because IE6 uses an ActiveX object, while virtually everything else uses XMLHttpRequest.

Right now I don't have any clue how to, well basically prototype/extend/overload (?) ActiveXObject("Microsoft.XMLHTTP"). This is what I am currently researching...does anybody know offhand?

Under each of the browsers I tested above, this works with AJAX requests from a generic object, and also from the jquery and prototype frameworks. I know there are other frameworks out there, but IMO these 2 are the major ones. I might possibly QA MooTools, but other than that, I'm fine with only testing those.

If Anybody wants to contribute by testing and posting results about other browsers and/or frameworks, it would be appreciated :)


For IE 6 compatibility, how about :

<script type='text/javascript'>
  var s_ajaxListener = new Object();

  // Added for IE support
  if (typeof XMLHttpRequest === "undefined") {
    XMLHttpRequest = function () {
      try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
      catch (e) {}
      try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
      catch (e) {}
      try { return new ActiveXObject("Microsoft.XMLHTTP"); }
      catch (e) {}
      throw new Error("This browser does not support XMLHttpRequest.");
    };
  }

  s_ajaxListener.tempOpen = XMLHttpRequest.prototype.open;
  s_ajaxListener.tempSend = XMLHttpRequest.prototype.send;
  s_ajaxListener.callback = function () {
    // this.method :the ajax method used
    // this.url    :the url of the requested script (including query string, if any) (urlencoded) 
    // this.data   :the data sent, if any ex: foo=bar&a=b (urlencoded)
  }

  XMLHttpRequest.prototype.open = function(a,b) {
    if (!a) var a='';
    if (!b) var b='';
    s_ajaxListener.tempOpen.apply(this, arguments);
    s_ajaxListener.method = a;  
    s_ajaxListener.url = b;
    if (a.toLowerCase() == 'get') {
      s_ajaxListener.data = b.split('?');
      s_ajaxListener.data = s_ajaxListener.data[1];
    }
  }

  XMLHttpRequest.prototype.send = function(a,b) {
    if (!a) var a='';
    if (!b) var b='';
    s_ajaxListener.tempSend.apply(this, arguments);
    if(s_ajaxListener.method.toLowerCase() == 'post')s_ajaxListener.data = a;
    s_ajaxListener.callback();
  }
</script>

참고URL : https://stackoverflow.com/questions/3596583/javascript-detect-an-ajax-event

반응형