JavaScript的:检测AJAX请求 [英] JavaScript: Detect AJAX requests

查看:111
本文介绍了JavaScript的:检测AJAX请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法来检测与通用的JavaScript(不使用框架)?

Is there any way to detect global AJAX calls (particularly responses) on a web page with generic JavaScript (not with frameworks)?

我已经审查了这个问题:的JavaScript检测AJAX事件这里的计算器,并试图修补在接受答案的code到我的应用程序,但没有奏效。我以前要么让从来没有做过与AJAX什么,我不知道够不够来修改它的工作。

I've already reviewed the question "JavaScript detect an AJAX event", here on StackOverflow, and tried patching in the accepted answer's code into my application but it didn't work. I've never done anything with AJAX before either so, I don't know enough to modify it to work.

我不需要任何幻想,我只需要检测所有(具体,实际,但我不得不检测所有第一,从那里)AJAX响应和补丁,使他们成为使用if语句。所以,最后,我想是这样的:

I don't need anything fancy, I just need to detect all (specific, actually, but I'd have to detect all first and go from there) AJAX responses and patch them into an IF statement for use. So, eventually, I'd like something like:

if (ajax.response == "certainResponseType"){
    //Code
}

,例如

更新: 看来我要澄清,我不是试图发送一个请求 - 我正在开发一个内容脚本,我需要能够到的检测的网页的AJAX请求(而不是让我自己),这样我就可以执行一个功能是检测到响应的时候。

Update: It seems I should clarify that I'm not trying to send a request - I'm developing a content script and I need to be able to detect the web page's AJAX requests (not make my own), so I can execute a function when a response is detected.

推荐答案

这可能是一个有点棘手。这个怎么样?

This can be a bit tricky. How about this?

_send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function() {

    /* Wrap onreadystaechange callback */
    var callback = this.onreadystatechange;
    this.onreadystatechange = function() {             
         if (this.readyState == 4) {

             /* We are in response; do something, like logging or anything you want */

         }

         callback.apply(this, arguments);
    }

    _send.apply(this, arguments);
}

我没有测试它,但它看起来或多或少的罚款。

I didn't test it, but it looks more or less fine.

请注意,如果使用框架(如jQuery的),它可能无法工作,因为他们可能会覆盖的onreadystatechange 呼叫后发送(我认为jQuery不会)。或者,他们可以覆盖发送办法(但这是不可能的)。因此它是一种部分解决方案。

Note that it may not work if you use frameworks (like jQuery), because they may override onreadystatechange after calling send (I think jQuery does). Or they can override send method (but this is unlikely). So it is a partial solution.

这篇关于JavaScript的:检测AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆