我一直在研究一个使用html5和最新版jquery的ajax文件加载器.关于使用基于ajax的新promise的进程回调,我感到很困惑.例如,通知功能.是自动调用吗?或者我需要为它编写处理程序.在我目前的代码中......显然是一段摘录.进程回调永远不会被击中.我也意识到有插件可用,但我不能使用它们.
var ajaxFileUpload = new $.ajax({
type:'POST',
url:"/popup/file_upload.php",
data:_private.appendFormData(file),
contentType:false,
processData:false
}).progress(function (event) {
console.log(event);
})
.done(function (response) {
console.log("done");
})
.fail(function (event) {
console.log("fail");
})}};
Run Code Online (Sandbox Code Playgroud)
如果你想上传一个进度条,你可以查看https://github.com/malsup/form/blob/master/jquery.form.js第292-309行(这是一个jquery插件,但你可以拉出来在没有插件的情况下使用的小部分).
s.xhr = function() {
var xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
options.uploadProgress(event, position, total, percent);
}, false);
}
return xhr;
};
Run Code Online (Sandbox Code Playgroud)
如果您想下载进度条,可以查看http://www.w3.org/TR/progress-events/以获取示例代码.您的服务器必须Content-Length在响应标头上给出相应的工作.
var progressBar = document.getElementById("p"),
client = new XMLHttpRequest()
client.open("GET", "magical-unicorns")
client.onprogress = function(pe) {
if(pe.lengthComputable) {
progressBar.max = pe.total
progressBar.value = pe.loaded
}
}
client.onloadend = function(pe) {
progressBar.value = pe.loaded
}
client.send()
Run Code Online (Sandbox Code Playgroud)
如果你正在运行一个报告,需要一段时间,你想服务器处理的进展情况,可能我建议改变它是多个Ajax请求:beginFoo,getFooProgress,getFooResult.其他方法包括使用COMET或Websocket连接来传达来自服务器的进度,或者在初始ajax请求等待响应时单独提取web服务.
如果你想要一个进步html5元素:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress.
| 归档时间: |
|
| 查看次数: |
9012 次 |
| 最近记录: |