JQuery is a 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. Which is giving binary data as a response and you'll discover that it does don't work F want do an AJAX request Or 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 the jQuery still does not support HTML5 XMLHttpRequest level 2 binary data type Requests–there is even A bug in the JQuery bug tracker, which asks for this feature. Although there is a long discussion about this subject on the GitHub, it seems so this feature would not become part of J Query soon.
To find a solution for this problem, we had to modify XMLHttpRequest itself. To read binary data correctly, we had to treat response type as BLOB data type.
var xhr = new XMLHttpRequest (); Xhr.open (' GET ', '/my/image/name.png ', true); Xhr.responsetype = ' blob '; xhr.onload = Function (e) { if (this.status = =) { //Get binary data as a response var blob = this.response; }}; Xhr.send ();
But what happens if we had to directly modify received binary data? XHR Level 2 also introduces "ArrayBuffer" response type. An ArrayBuffer was a generic fixed-length container for binary data. They is super handy if you need a generalized buffer of raw data, but the real power is so you can create "views" of th e underlying data using JavaScript typed arrays.
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 ();
This request creates a unsigned 8-bit integer array from data buffer. ArrayBuffer is especially useful if you have to read data for WebGL project, WebSocket or Canvas 2D
Binary data ajax Tranport for JQuery
Sometimes making complete fallback to XMLHttpRequest isn't a good idea, especially if you want to keep JQuery code clean and understandable. To solve the problem, JQuery allows us to create Ajax Transports–plugins, which is created to make custom Ajax request S.
We are "binary" Ajax transport based on our previous example. This Ajax transport creates new XMLHttpRequest and passes all the received data back to the jQuery.
/** * * jquery.binarytransport.js * * @description. JQuery Ajax Transport for making binary data type requests. * @version 1.0 * @author Henry algus <[email protected]> * *///Use this Transport for "binary" data Type$.aja Xtransport ("+binary", Function (options, originaloptions, JQXHR) {//check for conditions and support for BLOB/ARRAYBU Ffer 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,t ype = Options.type,async = Options.async | | true,//blob or Arraybuffer. Default is Blobdatatype = Options.responsetype | | "Blob", data = Options.data | | Null,username = options.Username | | Null,password = Options.password | | Null Xhr.addeventlistener (' Load ', function () {var data = {};d ata[options.datatype] = xhr.response;//make callback and send dat Acallback (Xhr.status, Xhr.statustext, data, xhr.getallresponseheaders ()); }); Xhr.open (type, URL, async, username, password);//Setup Custom Headersfor (var i in headers) {Xhr.setrequestheader (I, hea Ders[i]);} Xhr.responsetype = DataType; Xhr.send (data); }, Abort:function () {jqxhr.abort (); } }; }});
For the script to work correctly, ProcessData must is set to false, otherwise jQuery would try to convert received data in To string, but fails.
Now it's possible to read binary data using usual jQuery syntax:
$.ajax ({ URL: "/my/image/name.png", Type: "GET", dataType: "Binary", Processdata:false, Success:function (Result) { //do something with binary data }});
If you want receive ArrayBuffer as response type, you can use the Responsetype parameter while creating Ajax request:
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 the "header" parameter and set its value as a object, which has list of headers:
$.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 execution
It 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 has 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 doe s 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.
Reading binary data using JQuery Ajax