HTML5 Ajax 2.0標準中,增強了Ajax的許多功能,包括髮送FormData資料,上傳資料進度條等諸多功能。但實際上,Ajax可以位元組發送位元據。
發送位元據
var oReq = new XMLHttpRequest();oReq.open("POST", url, true);oReq.onload = function (oEvent) {// Uploaded.};var blob = new Blob(['abc123'], {type: 'text/plain'});oReq.send(blob);
或者
var myArray = new ArrayBuffer(512);var longInt8View = new Uint8Array(myArray);for (var i=0; i< longInt8View.length; i++) {longInt8View[i] = i % 255;}var xhr = new XMLHttpRequest;xhr.open("POST", url, false);xhr.send(myArray);
接收位元據
var oReq = new XMLHttpRequest();oReq.open("GET", "/myfile.png", true);oReq.responseType = "arraybuffer";oReq.onload = function (oEvent) {var arrayBuffer = oReq.response; // Note: not oReq.responseTextif (arrayBuffer) {var byteArray = new Uint8Array(arrayBuffer);for (var i = 0; i < byteArray.byteLength; i++) {}}};oReq.send(null);
當然,如上設定只能是文本類型,如果是Blob類型,那麼如下即可
var oReq = new XMLHttpRequest();oReq.open("GET", "/myfile.png", true);oReq.responseType = "arraybuffer";oReq.onload = function(oEvent) {var blob = new Blob([oReq.response], {type: "image/png"});// ...};oReq.send();
或者
var oReq = new XMLHttpRequest();oReq.open("GET", "/myfile.png", true);oReq.responseType = "blob";oReq.onload = function(oEvent) {var blob = oReq.response;// ...};oReq.send();
如果你使用的是舊版本的瀏覽器,那麼載入二進位可以如下
function load_binary_resource(url) {var req = new XMLHttpRequest();req.open('GET', url, false);//XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]req.overrideMimeType('text\/plain; charset=x-user-defined');req.send(null);if (req.status != 200) return '';return req.responseText;}
注意:x-user-defined告訴瀏覽器不要解析資料
以上所述是小編給大家介紹的Win7工作列Ajax發送和接收二進位位元組流資料的方法的相關知識,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!