如果请求失败返回原始 post 数据

Returning original post data if request fails

我知道我可以用全局来做到这一点,但如果可以的话,我想成为面向对象的。如果我的请求响应 returns 对于那个 'ok' 值是错误的,我想记录最初发布的数据。请求对象上的侦听器函数是否可以访问该数据? 谢谢!

function reqListener () {
        var data = this.responseText;
        var jsonResponse = JSON.parse(data);
        if (jsonResponse['ok'] == false) {
            //Here I want to log the data that I originally posted
            console.log(__TheFormDataThatWasPassedtoSend__);
        }
    }

var xhr = new XMLHttpRequest();
    xhr.addEventListener("load",reqListener);
    xhr.open('POST',urltopostto, true);

    // Set up a handler for when the request finishes.
    xhr.onload = function () {
      if (xhr.status === 200) {
        // File(s) uploaded.
        console.log('Uploaded');
      } else {
        alert('An error occurred!');
      }
    };
    xhr.send(formData);

因此,您遇到的问题是,当 eventListener 实际触发时,您需要使用创建 eventListener 时已知的数据。以下是使用 formData

执行此操作的代码
function reqListener (formData) {
        var data = this.responseText;
        var jsonResponse = JSON.parse(data);
        if (jsonResponse['ok'] == false) {
            console.log(formData);
        }
    }

var xhr = new XMLHttpRequest();
    xhr.addEventListener("load", function() { reqListener.call(this,formData) });
    xhr.open('POST',urltopostto, true);

    // Set up a handler for when the request finishes.
    xhr.onload = function () {
      if (xhr.status === 200) {
        // File(s) uploaded.
        console.log('Uploaded');
      } else {
        alert('An error occurred!');
      }
    };
    xhr.send(formData);