Last active
December 14, 2015 04:29
-
-
Save OmShiv/5028358 to your computer and use it in GitHub Desktop.
Binary data in the OLD Web and the new HTML5 Web, via AJAX
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
** 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