beforeSend xhr对象:未​​捕获的TypeError:无法读取未定义的属性'addEventListener' [英] beforeSend xhr object : Uncaught TypeError: Cannot read property 'addEventListener' of undefined

查看:122
本文介绍了beforeSend xhr对象:未​​捕获的TypeError:无法读取未定义的属性'addEventListener'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不断收到此错误:

未捕获的TypeError:无法读取未定义的属性'addEventListener' 我试图在其中应用进度"事件侦听器的地方

Uncaught TypeError: Cannot read property 'addEventListener' of undefined Where I am trying to apply an "progress" event listener

为什么会出现此错误?

  <script type="text/javascript">
      $(document).ready(function(){
        $("#wb_bc_file_field").change(function(){
          var formdata = new FormData();
          formdata.append("video",$("#wb_bc_file_field")[0]);
          // Start Ajax Call
          $.ajax({
            url:"server.php",
            beforeSend:function(xhr){
              xhr.upload.addEventListener("progress", function(event){

              });
            },
            processData:false,
            contentType:"multipart/form-data; charset=UTF-8",

            data:formdata
          }).done(function(){
            console.log("Request is complete.");
          }).fail(function(){
            console.log("Request has failed.");
          }).always(function(){
            console.log("Request has closed.");
          }); // End .ajax
        }); // End .change
      }); // End .ready
  </script>

这是整个脚本的 jsfiddle .由于没有php文件,它将给出一个错误,但现在还可以.

Here is a jsfiddle of the entire script. Since there is no php file it will give an error but thats fine for now.

推荐答案

我认为该错误是由于甚至在我们开始发起XHR请求之前调用上载事件引起的.

I think the error is causing because of calling the upload event even before we start initiating the XHR request.

 $.ajax({
        url:"server.php",
        beforeSend:function(xhr){
          xhr.upload.addEventListener("progress", function(event){

          });
        },
       ...

与代码中的一样,我们在beforeSend中调用xhr.upload.addEventListener("progress".由于我们尚未启动请求,(我们在beforeSend中)我们不能有任何xhr.upload对象.我们可以通过将代码移至xhr而不是beforeSend来解决此问题.

As in the code we are calling xhr.upload.addEventListener("progress" in beforeSend. Since we didn't start the request yet, (we are in beforeSend) we can't have any xhr.upload object. We can solve this by moving code to xhr instead of beforeSend.

注意:您需要jQuery版本> 1.5.1

$.ajax({
  url:"server.php",    
  xhr: function()
   {
   var xhr = new window.XMLHttpRequest();
   //Upload progress
   xhr.upload.addEventListener("progress", function(evt){
    ...
   }, false);
  return xhr;
 },

以下是文档: http://api.jquery.com /jquery.ajax/#jQuery-ajax-url-settings

这篇关于beforeSend xhr对象:未​​捕获的TypeError:无法读取未定义的属性'addEventListener'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆