问题描述
我不断收到此错误:
未捕获的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'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!