XMLHttpRequest:需要使用来自 ajax 的成功和错误函数

XMLHttpRequest: need to use success and error functions from ajax

我有这个 ajax post 函数 运行 单击上传按钮时,文件会上传到服务器,服务器会查看是否有任何错误,如果有错误, 它通过 req.end(); 函数通知用户。问题是,从那时起,我已经转移到 XMLHttpRequest()(使用它提供的 onprogress 函数),但我仍然需要使用 ajax 中的那些成功和错误函数。有没有办法通过 XMLHttpRequest 以某种方式使用它们?谢谢!

这是我目前的代码:

var xhrVideo = new XMLHttpRequest();
xhrVideo.open('POST', '/uploadVideo', true);
xhrVideo.upload.onprogress = function(e) {
  if (e.lengthComputable) {
    $('.videoProgress').html(((e.loaded / e.total) * 100).toFixed(0)+'%');
  }
};
var videoForm = new FormData($('.videoUploadForm')[0]);
xhrVideo.send(videoForm);

和 ajax 代码:

var videoData = new FormData($('.videoUploadForm')[0]);
$.ajax({
  url: '/uploadVideo',
  type: 'POST',
  data: videoData,
  cache: false,
  contentType: false,
  processData: false,
  mimeType:"multipart/form-data",
  success: function(data){
    switch(data){
      case '1':
        alert('Wrong Video File Extension');
        break;
      case '2':
        alert('Wrong Image File Type');
        break;
    }
  },
  error: function(data){
    alert('Something went wrong! Please reload this page')
  }
});

loaderror 事件使用侦听器。

为成功事件添加侦听器的示例。

xhrVideo.addEventListener('load', function(e) {

注意: 必须在 send() 函数之前添加监听器

此外,我建议您阅读整个 article 关于使用 XMLHttpRequest() 的内容。

就我个人而言,我喜欢使用 jquery ajax 而不是纯粹的 javascript .. 因此您可以将 xhr 与 ajax 一起使用并掌握进度以及加载事件

xhr (default: ActiveXObject when available (IE), the XMLHttpRequest otherwise) Type: Function() Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory.

在你的代码中你可以像这样使用它

$.ajax({
        xhr: function(){
            var xhr = new window.XMLHttpRequest();
            //Upload progress
            xhr.upload.addEventListener("progress", function(evt){
                if (evt.lengthComputable) {
                    var percentComplete = (evt.loaded / evt.total) * 100;
                      //Do something with upload progress
                        $('.videoProgress').html(Math.round(percentComplete)+"% uploaded");
                    }
                }
            }, false);
            xhr.upload.addEventListener("load", function(evt){
                evt.preventDefault();

            },false);
           return xhr;
        },
        // reset of your ajax code