如果请求失败,则返回原始帖子数据

时间:2018-03-20 21:07:04

标签: javascript jquery xmlhttprequest listener response

我知道我可以用全局做到这一点,但如果可以的话,我希望能够面向对象。如果我的请求响应为该'ok'值返回false,我想记录最初发布的数据。请求对象上的侦听器函数是否可以访问该数据? 谢谢!

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

1 个答案:

答案 0 :(得分:1)

因此,当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);