如何获取附加到 AJAX 请求的事件的元信息?

发布于 2024-12-09 20:18:55 字数 640 浏览 0 评论 0原文

我想用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浮华 2024-12-16 20:18:55

利用 javascript 具有闭包这一事实。

xhr.open('POST',' /path/to/upload', true);
xhr.setRequestHeader("X-File-Name", file.name); //  you have file.name here
xhr.setRequestHeader("X-File-id", md5(filename+file.size));

xhr.upload.onprogress = function(evt) {
    console.log(file.name); // so its available here because of closures
    var percent = evt.loaded/evt.total*100;
    var $target = $(evt.target);
    console.log('ok');
    console.log($target);
    console.log('Upload progress: ' + percent + '%');
}

xhr.send(file);

在这个简单的示例中,因为您在 onprogress 回调中使用 file.name,所以 javascript 知道通过回调获取该值并使其可用。

Take advantage of the fact that javascript has closures.

xhr.open('POST',' /path/to/upload', true);
xhr.setRequestHeader("X-File-Name", file.name); //  you have file.name here
xhr.setRequestHeader("X-File-id", md5(filename+file.size));

xhr.upload.onprogress = function(evt) {
    console.log(file.name); // so its available here because of closures
    var percent = evt.loaded/evt.total*100;
    var $target = $(evt.target);
    console.log('ok');
    console.log($target);
    console.log('Upload progress: ' + percent + '%');
}

xhr.send(file);

In that simple example, because you use file.name in the onprogress callback, javascript knows to take the value with the callback and makes it available.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文