如何获取附加到 AJAX 请求的事件的元信息?
我想用ajax上传文件到服务器并定期更新进度条。 在 javascript 中,我有:
xhr.open('POST',' /path/to/upload', true);
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-id", md5(filename+file.size));
xhr.upload.addEventListener('progress', onprogressHandler, false);
xhr.send(file);
在事件处理程序中,我有:
function onprogressHandler(event) {
var percent = event.loaded/event.total*100;
var $target = $(event.target);
console.log('ok');
console.log($target);
console.log('Upload progress: ' + percent + '%');
}
如何获取此事件附加到的 xhr 请求的信息,例如我发送哪个文件,以便我可以更新与该文件对应的进度条?
I want to ajax upload a file to the server and update the progress bar peroidically.
In the javascript, I have:
xhr.open('POST',' /path/to/upload', true);
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-id", md5(filename+file.size));
xhr.upload.addEventListener('progress', onprogressHandler, false);
xhr.send(file);
In the event handler, I have :
function onprogressHandler(event) {
var percent = event.loaded/event.total*100;
var $target = $(event.target);
console.log('ok');
console.log($target);
console.log('Upload progress: ' + percent + '%');
}
How can I get the information of the xhr request this event is attached to, like which file am I sending so that I can update the progress bar corresponding to that file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
利用 javascript 具有闭包这一事实。
在这个简单的示例中,因为您在
onprogress
回调中使用file.name
,所以 javascript 知道通过回调获取该值并使其可用。Take advantage of the fact that javascript has closures.
In that simple example, because you use
file.name
in theonprogress
callback, javascript knows to take the value with the callback and makes it available.