检查XHR和progress-event的浏览器function

关注这个问题:

jQuery AJAX上传大文本字段的进度

如何使它与旧版浏览器兼容?

正如您在上面的问题中所看到的,我依赖于XHR和progress-event。 现在对于旧浏览器,我需要检测它们是否不具备其中一个,因此我可以跳过进度条并仍然可以制作我的AJAXpost。

我认为它可以像这样工作:

$.ajax({ xhr: function() { var xhr = $.ajaxSettings.xhr(); if (xhr instanceof window.XMLHttpRequest) { xhr.addEventListener('progress', function(event) { if (event.lengthComputable) { progressPercent = Math.round(event.loaded/event.total*100)+'%'; $loader.width(progressPercent); } }, false); }else{ alert('XHR is no instance of window.XMLHttpRequest'); } return xhr; }, type: "POST", ... 

但我不知道这是否存了,或者我还有什么需要检查的。

谢谢!

对于接近完全安全的东西,您可以使用try / catch / finally结构:

 $.ajax({ xhr: function() { var xhr = $.ajaxSettings.xhr(); try { xhr.addEventListener('progress', function(event) { if (event.lengthComputable) { $loader.width(Math.round(event.loaded / event.total * 100) + '%'); } }, false); } catch(err) { //Progess not available //Take appropriate action - eg hide the progress thermometer $loader.hide(); } finally { return xhr; } }, type: "POST", ... }):