简体   繁体   English

捕获ajax请求及其POST数据

[英]Capture ajax request and its POST data

I want to capture an ajax request and its POST-data but haven't found any way of doing it. 我想捕获一个ajax请求及其POST数据,但尚未找到任何方法。

I've been trying with: XMLHttpRequest.prototype.open but haven't found any way of capturing the POST data using it. 我一直在尝试:XMLHttpRequest.prototype.open,但是还没有找到使用它捕获POST数据的任何方法。

I suppose this is what I'd like to do: 我想这就是我想做的:

(function(open) {
    XMLHttpRequest.prototype.open = function (method, url, async) {
        this.addEventListener('readystatechange', function () {
            if(url.indexOf("the-url-i-want-to-capture") !== -1 && this.readyState === 4 && this.status === 200) {
                // do ... something ... with the POST data
            }
        }, false);
        open.call(this, method, url, async);
    };
})(XMLHttpRequest.prototype.open);

When you are working with native ajax XMLHttpRequest object, do not use prototype to access open , but first declare the variable and then use all the methods that it offers, like open , send etc. 当使用本地ajax XMLHttpRequest对象时,请勿使用原型访问open ,而是先声明变量,然后使用其提供的所有方法,例如opensend等。

Also note that you can't intercept and capture data because FormData objects are not stringifiable objects (hint: images?). 还要注意,您不能截取和捕获数据,因为FormData对象不是可字符串化的对象(提示:图像?)。 only if you are using GET method you can see data in the url . 仅当您使用GET方法时,您才能在url看到数据。

I've added example for you to see response from POST request 我添加了示例供您查看POST请求的响应

See this page to get you started with all the details: https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started 请参阅此页面,以开始使用所有详细信息: https : //developer.mozilla.org/zh-CN/docs/Web/Guide/AJAX/Getting_Started

 (function(open) { // declare new http client var req = new XMLHttpRequest(); // define what to do after req finishes req.onreadystatechange = function(){ if(req.readyState === XMLHttpRequest.DONE) console.log( req.responseText ); }; // start our POST req req.open('POST', 'https://jsonplaceholder.typicode.com/posts?test', true); // sent it req.send(); })(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM