beforeSend xhr object : Uncaught TypeError: Cannot read property 'addEventListener' of undefined

拜拜、爱过 提交于 2019-12-11 09:41:54

问题


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:


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



来源:https://stackoverflow.com/questions/23140054/beforesend-xhr-object-uncaught-typeerror-cannot-read-property-addeventlisten

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!