使用jQuery AJAX读取二进制数据
2015-10-10 12:44
585 查看
READING BINARY DATA USING JQUERY AJAX
http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/Query is an excellent tool to make web development easy and straightforward. It helps while doing DOM manipulation and makes Ajax requests painless across different browsers and platforms. But if you want make an Ajax request, which is giving binary data as a response, you will discover that it does not work for jQuery, at least for now. Changing “dataType” parameter to “text”, does not help, neither changing it to any other jQuery supported Ajax data type.
Problem here is that jQuery still does not support HTML5 XMLHttpRequest Level 2 binary data type requests – there is even a bug in jQuery bug tracker, which asks for this feature. Although there is a long discussion about this subject on the GitHub, it seems that this feature will not become part of jQuery soon.
To find a solution for this problem, we have to modify XMLHttpRequest itself. To read binary data correctly, we have to treat response type as blob data type.
123456789101112 | var xhr = new XMLHttpRequest();xhr.open('GET', '/my/image/name.png', true);xhr.responseType = 'blob'; xhr.onload = function(e) { if (this.status == 200) { // get binary data as a response var blob = this.response; }}; xhr.send(); |
12345678910 | var xhr = new XMLHttpRequest();xhr.open('GET', '/my/image/name.png', true);xhr.responseType = 'arraybuffer'; xhr.onload = function(e) { // response is unsigned 8 bit integer var responseArray = new Uint8Array(this.response); }; xhr.send(); |
Binary data ajax tranport for jQuery
Sometimes making complete fallback to XMLHttpRequest is not a good idea, especially if you want to keep jQuery code clean and understandable. To solve this problem, jQuery allows us to create Ajax transports – plugins, which are created to make custom Ajax requests.Our idea is to make “binary” Ajax transport based on our previous example. This Ajax transport creates new XMLHttpRequest and passes all the received data back to the jQuery.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 | /** * * jquery.binarytransport.js * * @description. jQuery ajax transport for making binary data type requests. * @version 1.0 * @author Henry Algus <henryalgus@gmail.com> * */ // use this transport for "binary" data type$.ajaxTransport("+binary", function(options, originalOptions, jqXHR){ // check for conditions and support for blob / arraybuffer response type if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob))))) { return { // create new XMLHttpRequest send: function(headers, callback){ // setup all variables var xhr = new XMLHttpRequest(), url = options.url, type = options.type, async = options.async || true, // blob or arraybuffer. Default is blob dataType = options.responseType || "blob", data = options.data || null, username = options.username || null, password = options.password || null; xhr.addEventListener('load', function(){ var data = {}; data[options.dataType] = xhr.response; // make callback and send data callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders()); }); xhr.open(type, url, async, username, password); // setup custom headers for (var i in headers ) { xhr.setRequestHeader(i, headers[i] ); } xhr.responseType = dataType; xhr.send(data); }, abort: function(){ jqXHR.abort(); } }; }}); |
Now it is possible to read binary data using usual jQuery syntax:
123456789 | $.ajax({ url: "/my/image/name.png", type: "GET", dataType: "binary", processData: false, success: function(result){ // do something with binary data }}); |
1 | responseType:'arraybuffer' |
How to setup custom headers?
It is possible to set multiple custom headers when you are making the request. To set custom headers, you can use “header” parameter and set its value as an object, which has list of headers:12345678910 | $.ajax({ url: "image.png", type: "GET", dataType: 'binary', headers:{'Content-Type':'image/png','X-Requested-With':'XMLHttpRequest'}, processData: false, success: function(result){ }}); |
Another options
Asynchronous or synchronous executionIt is possible to change execution type from asynchronous to synchrous when setting parameter “async” to false.
async:false,
Login with user name and password
If your script needs to have authentication during the request, you can use username and password parameters.
username:'john',
password:'smith',
Supported browsers
BinaryTransport requires XHR2 responseType, ArrayBuffer and Blob response type support from your browser, otherwise it does not work as expected. Currently most major browsers should work fine.Firefox: 13.0+ Chrome: 20+ Internet Explorer: 10.0+ Safari: 6.0 Opera: 12.10
Binary transport jQuery plugin is also available in my GitHub repository.
相关文章推荐
- jquery倒计时
- Jquery基础之DOM操作
- JQuery控制只输入数字,关闭输入法
- 使用jquery获取url及url参数的方法
- jquery 遍历集合
- jquery validator添加自定义方法
- jQuery制作瀑布流
- jqueryflot图表x轴坐标过长完美解决方案(转)
- JQuery将时间戳转换为时间
- jQuery实现仿新浪微博浮动的消息提示框(可智能定位)
- jquery 锚点滚动
- jQuery插件之ajaxFileUpload使用小结
- web前端有用的十个JQuery代码片段
- jQuery MiniUI 开发指南+API组件参考手册
- jquery.query-*.js 操作url
- jquery.query-*.js 操作url
- jquery获取兄弟元素
- jquery获取兄弟元素
- jquery对象和dom对象的相互转换
- myeclipse导入jquery.min.js文件打叉