This article mainly introduces the method of sending and receiving binary byte stream data in Ajax. It is very good and has reference value. Friends who are interested should take a look together
In the HTML5 Ajax 2.0 standard, enhancements It has many functions of Ajax, including sending FormData data, uploading data progress bar and many other functions. But in fact, Ajax can send binary data by bytes.
Send binary data
1 2 3 4 5 6 7 | var oReq = new XMLHttpRequest();
oReq.open( "POST" , url, true);
oReq.onload = function (oEvent) {
};
var blob = new Blob(['abc123'], {type: 'text/plain'});
oReq.send(blob);
|
Copy after login
or
1 2 3 4 5 6 7 8 | 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);
|
Copy after login
Receive binary data
1 2 3 4 5 6 7 8 9 10 11 12 | var oReq = new XMLHttpRequest();
oReq.open( "GET" , "/myfile.png" , true);
oReq.responseType = "arraybuffer" ;
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response;
if (arrayBuffer) {
var byteArray = new Uint8Array(arrayBuffer);
for ( var i = 0; i < byteArray.byteLength; i++) {
}
}
};
oReq.send(null);
|
Copy after login
Of course, the above setting can only be for text type. If it is Blob type, then the following can be done
1 2 3 4 5 6 7 8 | 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();
|
Copy after login
or
1 2 3 4 5 6 7 8 | var oReq = new XMLHttpRequest();
oReq.open( "GET" , "/myfile.png" , true);
oReq.responseType = "blob" ;
oReq.onload = function (oEvent) {
var blob = oReq.response;
};
oReq.send();
|
Copy after login
If you are using an old version Browser, then loading the binary can be as follows
1 2 3 4 5 6 7 8 9 | function load_binary_resource(url) {
var req = new XMLHttpRequest();
req.open('GET', url, false);
req.overrideMimeType('text\/plain; charset=x-user-defined');
req.send(null);
if (req.status != 200) return '';
return req.responseText;
}
|
Copy after login
Note: x-user-defined tells the browser not to parse the data
The above is what I compiled for everyone, I hope it will be helpful to everyone in the future.
Related articles:
Using Ajax technology to partially refresh product quantity and total price example code
Perfect solution to ajax access when encountering Session Invalid problem
The reason why ajax internal value cannot be called externally and the solution
The above is the detailed content of Ajax method for sending and receiving binary byte stream data. For more information, please follow other related articles on the PHP Chinese website!