准备状态更改不触发的功能

时间:2020-06-29 11:17:31

标签: javascript

我有以下应在xhr请求完成后打印“完成”的功能。

当用户将图像拖放到所见即所得的编辑器中并自动上传图像时,xhr请求就会启动。

<script>

    $(document).ready(function(){

        var oldXHR = window.XMLHttpRequest;

        function newXHR() {
            var realXHR = new oldXHR();
            realXHR.addEventListener("readystatechange", function() {
                if(realXHR.readyState==4 && realXHR.status==200){
                    afterAjaxComplete() //run your code here

                    console.log('done');

                }
            }, false);
            return realXHR;
        }
        window.XMLHttpRequest = newXHR;

    });

</script>

关于它为什么不触发的任何想法?

谢谢!

1 个答案:

答案 0 :(得分:0)

不能100%确定此处的要求,但此函数应返回XHR对象。

我还添加了第二个示例(参考源代码),该示例还包含一个readyStateChange,它触发的次数可能比使用时要多-请参阅其他事件处理程序以获取可能的见解。注意:由于CORS的阻塞,示例实际上并未在此处“运行”。

$(document).ready(function() {
  function newXHR() {
    const realXHR = new window.XMLHttpRequest();
    realXHR.addEventListener("readystatechange", function() {
      if (this.readyState == 4 && this.status == 200) {
        afterAjaxComplete(); //run your code here
        console.log('done');
      }
    }, false);
    return realXHR;
  }
  var myxhr = newXHR();

});
// borrowed from here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/loadend_event

const xhrButtonSuccess = document.querySelector('.xhr.success');
const xhrButtonError = document.querySelector('.xhr.error');
const xhrButtonAbort = document.querySelector('.xhr.abort');
const log = document.querySelector('.event-log');
const readylog = document.querySelector('.readyevent-log');

function handleEvent(e) {
  log.textContent = log.textContent + `${e.type}: ${e.loaded} bytes transferred\n`;
}

function handleReadyEvent(e) {
  readylog.textContent = readylog.textContent + `${e.type}: state: ${this.readyState }  status: ${this.status} r: ${this.response}\n`;
}

function addListeners(xhr) {
  xhr.addEventListener('loadstart', handleEvent);
  xhr.addEventListener('load', handleEvent);
  xhr.addEventListener('loadend', handleEvent);
  xhr.addEventListener('progress', handleEvent);
  xhr.addEventListener('error', handleEvent);
  xhr.addEventListener('abort', handleEvent);
  xhr.addEventListener('readystatechange', handleReadyEvent);
}

function runXHR(url) {
  log.textContent = '';

  const xhr = new XMLHttpRequest();
  addListeners(xhr);
  xhr.open("GET", url);
  xhr.send();
  return xhr;
}

xhrButtonSuccess.addEventListener('click', () => {
  runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg');
});

xhrButtonError.addEventListener('click', () => {
  runXHR('https://somewhere.org/i-dont-exist');
});

xhrButtonAbort.addEventListener('click', () => {
  runXHR('https://mdn.mozillademos.org/files/16553/DgsZYJNXcAIPwzy.jpg')
    .abort();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="controls">
  <input class="xhr success" type="button" name="xhr" value="Click to start XHR (success)" />
  <input class="xhr error" type="button" name="xhr" value="Click to start XHR (error)" />
  <input class="xhr abort" type="button" name="xhr" value="Click to start XHR (abort)" />
</div>

<textarea readonly class="event-log"></textarea>
<textarea readonly class="readyevent-log"></textarea>

jQuery ajax示例的完全未经测试的代码参考:https://api.jquery.com/jquery.ajax/

$(function() {
  $('#formbutton').on('click', function() {
    var formData = new FormData();
    formData.append('file', $('#uploadfile')[0].files[0]);

    var jxhr = $.ajax({
      url: 'savemyfileUrl',
      type: 'POST',
      data: formData,
      processData: false, // tell jQuery not to process the data
      contentType: false // tell jQuery not to set contentType
    }).done(function(data, textStatus, jqXHR) {
      console.log(data);
    }).fail(function(jqXHR, textStatus, errorThrown) {
      console.log(textStatus);
      console.log(errorThrown);
    }).always(function(dataOrjqXHR, textStatus, jqXHROrErrorThrown) {
      console.log("always" + textStatus);
    });

    jxhr.always(function(data) {
        console.log("another always");
      })
      .then(function(data, textStatus, jqXHR) {
        console.log("It is done" + textStatus);
      }, function(jqXHR, textStatus, errorThrown) {
        console.log("It failed" + textStatus);
      });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
  Something: <input type="text" value="example text">
  <button id="formbutton">GO</button>

</form>
File?: <input id="uploadfile" type="file">