ajax要求がjqueryの$.ajaxによって開始された場合、デフォルトでは、jqueryのグローバルAjaxイベントハンドラーを使用してAjaxイベントを聴くことができます。しかし、私が遭遇したのは、ネイティブJavaScriptで開始されたAjaxリクエストでしたので、この方法は機能しません。
次に、Pub/Subなどの他の方法がありますが、リクエストを開始するJSコードを変更することはできないため、パブリッシュをコードに追加することはありません。同様に、jQueryの.bindと.trigger使用できません。
最後に、カスタムイベントを使用しながら、直接override XMLHttpRequestを使用することにしました。
Stackoverflowを検索すると、悪者が信頼できない解決策を与えたことがわかりました。さて、私はあなたが見るためにそれを投稿します:
;(function(){var open = window.xmlhttprequest.prototype.open、send = window.xmlhttprequest.prototype.send、onreadedstatechange; function openreplacement(方法、URL、非同期、ユーザー、パスワード) if.onedystatechange = this.onedStateChange = onreadyStateChangEREDECHEMENT。 window.xmlhttprequest.prototype.open = openReplacement;このソリューションはすべてのXHR Eventsを聞くことができず、 readystatechangeイベントはsendメソッドを呼び出した後にのみ聴くため、 readyState = 1場合はイベントを聞くことができません。同時に、 sendメソッドを使用した後にonreadystatechangeのコールバック関数を設定すると、 overrideコードが再びoverride 、予想される効果は生成されません。
では、どうすればXHRを正しくオーバーライドできますか?コードを投稿して、見てみましょう。
;(function(){function ajaxeventtrigger(event){var ajaxevent = new customevent(event、{detail:this}); window.dispatchevent(ajaxevent);} var oldxhr = window.xmlhttprequest; function newxhr(){var realxhr = new oldxhr(); realxhr.addeventlistener( 'abort'、function(){ajaxeventtrigger.call( 'ajaxabort');}、false)、 'error'、function(){ajaxeventtrigger.call realxhr.addeventlistener( 'load'、function(){ajaxeventtrigger.call( 'ajaxload');}、false); realxhr.addeventlistener( 'timeout'、function(){ajaxeventtrigger.call(this、 'ajaxtimeout');}、false)( 'loadend'、function(){ajaxeventtrigger.call realxhr.addeventlistener( 'readystatechange'、function(){ajaxeventtrigger.call( 'ajaxreadystechange');}、false)} window.xmlhttprequest = newxhr;}これにより、カスタムイベントがXHRに追加されます。電話する方法は?
var xhr = new xmlhttprequest(); window.addeventlistener( 'ajaxreadystatechange'、function(e){console.log(e.detail); // xmlhttprequestオブジェクト}); window.addeventlistener( 'ajaxabort'、function(e){console.log(e.detail.responsetext); // xhr}によって返されるコンテンツ); xhr.open( 'get'、 'info.json'); xhr.send();通常のreadystatechangeと他のイベントhandlerによって返されるe XMLHttpRequestオブジェクトであるが、 e CustomEventメソッドajaxReadyStateChangeおよびe.detailのイベントハンドラーによって返さXMLHttpRequestことに注意してください。 Ajax要求によって返されるコンテンツを取得するe.responseTextも、 e.detail.responseTextに変更する必要があります。
同時に、 addEventListenerメソッドは、 XHRインスタンスではなく、 window 对象にマウントする必要があります。
上記のコードはCustomEventコンストラクターを使用するため、最新のブラウザでは通常使用できますが、IEでもIE 11でさえサポートしていないため、 Polyfill追加する必要があります。これは次のようになります。
;(function(){if(typeof windof.customevent === "function")return false; function customevent(event、params){params = params || {bubbles:false、cancelable:false、false、undefined}; return evt; customevent.prototype.event.prototype; customevent;}) windo.xmlhttprequest; ajaxeventtrigger.call( 'ajaxerror')、false); ajaxeventtrigger.call( 'ajaxloadstart')、false); ajaxeventtrigger.call( 'ajaxprogress')、false); ajaxeventtrigger.call( 'ajaxloadend')、false); newxhr;})();この時点で、IE 9+、Chrome 15+、Firefox 11+、Edge、Safari 6.1+、およびOpera 12.1+で喜んで使用できます。上記はこの記事のすべての内容です。気に入っていただければ幸いです。