beforeSend xhr object : Uncaught TypeError: Cannot

2019-08-03 08:57发布

I keep getting this error:

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

Why am I getting this error?

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

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

1条回答
霸刀☆藐视天下
2楼-- · 2019-08-03 09:44

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

          });
        },
       ...

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.

Note: you need jQuery version > 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;
 },

Here's the documentation: http://api.jquery.com/jquery.ajax/#jQuery-ajax-url-settings

查看更多
登录 后发表回答