jQuery equivalent to XMLHttpRequest#39;s upload?(jQuery相当于XMLHttpRequest的上传?)
问题描述
使用 HTML5 的文件 API,上传是通过 XMLHttpRequest 中名为 upload 的对象进行的.This 是我正在使用的教程(以及 Google 缓存镜像,因为它目前已关闭).这是相关部分:
Working with HTML5's File API, the upload is made via an object called upload in the XMLHttpRequest. This is the tutorial I'm working with (and the Google cache mirror since it's down at the moment). This is the relevant part:
// Uploading - for Firefox, Google Chrome and Safari
xhr = new XMLHttpRequest();
// Update progress bar
xhr.upload.addEventListener("progress", function (evt) {
如您所见,为了跟踪上传进度,XMLHttpRequest 对象有一个名为 upload 的属性,我们可以添加一个事件处理程序.
As you can see, to track the upload progress, the XMLHttpRequest object has a property named upload, which we can add an event handler.
我的问题是:有 jQuery 等价物吗?.我试图让代码尽可能干净并尽可能兼容跨浏览器,因为只要微软认为这是一个好主意(尽管它听起来像 它将在 2012 年或 2013 年).
My question is: has jQuery an equivalent?. I'm attempting to leave the code as clean as and cross-browser compatible as possible, for whenever Microsoft thinks it's a good idea (although it sounds like it will be in 2012 or 2013).
推荐答案
这是我想出的解决问题的方法.$.ajax() 调用允许提供一个回调来生成 XHR.我只是在调用请求之前生成一个,设置它,然后创建一个闭包以在 $.ajax() 需要它时返回它.如果他们只是通过 jqxhr 访问它会容易得多,但他们没有.
Here is what I came up with to get around the issue. The $.ajax() call allows to provide a callback to generate the XHR. I just generate one before calling the request, set it up and then create a closure to return it when $.ajax() will need it. It would have been much easier if they just gave access to it through jqxhr, but they don't.
var reader = new FileReader();
reader.onloadend = function (e) {
var xhr, provider;
xhr = jQuery.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function (e) {
// ...
}, false);
}
provider = function () {
return xhr;
};
// Leave only the actual base64 component of the 'URL'
// Sending as binary ends up mangling the data somehow
// base64_decode() on the PHP side will return the valid file.
var data = e.target.result;
data = data.substr(data.indexOf('base64') + 7);
$.ajax({
type: 'POST',
url: 'http://example.com/upload.php',
xhr: provider,
dataType: 'json',
success: function (data) {
// ...
},
error: function () {
// ...
},
data: {
name: file.name,
size: file.size,
type: file.type,
data: data,
}
});
};
reader.readAsDataURL(file);
这篇关于jQuery相当于XMLHttpRequest的上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:jQuery相当于XMLHttpRequest的上传?
基础教程推荐
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
