本文介绍了添加&QUOT;勾&QUOT;一个网页上的所有AJAX请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想知道这是否是可能的钩子为每一个Ajax请求(无论是因为它是要被发送,或事件)和执行的操作。在这一点上我假设有在页面上的其他第三方脚本。其中的一些可能使用jQuery,而有的则没有。这可能吗?I'd like to know if it's possible to "hook" into every single AJAX request (either as it's about to get sent, or on events) and perform an action. At this point I'm assuming that there are other third-party scripts on the page. Some of these might use jQuery, while others do not. Is this possible?推荐答案按aviv's回答,我做了一个小调查,这是我想出了。我不知道,这一切都那么有用作为每在过程中的的脚本和意见将只对使用本机XMLHtt prequest对象浏览器。我认为它会工作,如果JavaScript库都在使用,因为它们会请尽量使用原生对象。Inspired by aviv's answer, I did a little investigating and this is what I came up with.I'm not sure that it's all that useful as per the comments in the script and of course will only work for browsers using a native XMLHttpRequest object.I think it will work if javascript libraries are in use as they will use the native object if possible.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}); 这篇关于添加&QUOT;勾&QUOT;一个网页上的所有AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-12 04:29