捕获ajax请求及其POST数据

时间:2017-11-27 12:21:15

标签: javascript ajax

我想捕获一个ajax请求及其POST数据,但还没有找到任何方法。

我一直在尝试使用:XMLHttpRequest.prototype.open但是没有找到使用它捕获POST数据的任何方法。

我想这就是我想要做的事情:

(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);

1 个答案:

答案 0 :(得分:0)

当您使用本机ajax XMLHttpRequest对象时,请不要使用prototype来访问open,而是先声明变量,然后使用它提供的所有方法,例如opensend等。

另请注意,您无法拦截和捕获数据,因为FormData对象不是可字符串对象(提示:图像?)。只有在使用GET方法时,您才能看到url

中的数据

我添加了一个示例供您查看POST请求的响应

请参阅此页面,开始了解所有详细信息:https://developer.mozilla.org/en-US/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();
})();

相关问题