【问题标题】:Returning original post data if request fails如果请求失败,则返回原始帖子数据
【发布时间】:2018-03-20 21:07:04
【问题描述】:

我知道我可以使用全局变量来做到这一点,但如果可以的话,我想成为面向对象的。如果我的请求响应为那个 '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);

【问题讨论】:

    标签: javascript jquery xmlhttprequest listener response


    【解决方案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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-09
      • 2015-07-15
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      相关资源
      最近更新 更多