Skip to content

Instantly share code, notes, and snippets.

@OmShiv OmShiv/bin-ajax.js
Last active Dec 14, 2015

Embed
What would you like to do?
Binary data in the OLD Web and the new HTML5 Web, via AJAX
/*
** OLD
*/
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/image.png', true);
// Trick to pass bytes through unprocessed.
xhr.overrideMimeType('text/plain; charset=x-user-defined')
xhr.onreadystatechange = function(e) {
if (this.readyState == 4 && this.status == 200) {
var binStr = this.responseText;
for (var i = 0, len = binStr.length; i < len; ++i) {
var c = binStr.charCodeAt(i);
//String.fromCharCode(c & 0xff)
var byte = c & 0xff; // byte at offset i
}
}
};
xhr.send();
/*
** HTML5 - XmlHttpRequest2 (The new Web)
*/
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/image.png', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var uInt8Array = new Uint8Array(this.response); // Note: not xhr.responseText
var byte3 = uInt8Array[4]; // byte at offset 4
}
};
xhr.send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.