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
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);
or
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);
Receive binary data
var oReq = new XMLHttpRequest(); oReq.open("GET", "/myfile.png", true); oReq.responseType = "arraybuffer"; oReq.onload = function (oEvent) { var arrayBuffer = oReq.response; // Note: not oReq.responseText if (arrayBuffer) { var byteArray = new Uint8Array(arrayBuffer); for (var i = 0; i < byteArray.byteLength; i++) { } } }; oReq.send(null);
Of course, the above setting can only be for text type. If it is Blob type, then the following can be done
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();
or
var oReq = new XMLHttpRequest(); oReq.open("GET", "/myfile.png", true); oReq.responseType = "blob"; oReq.onload = function(oEvent) { var blob = oReq.response; // ... }; oReq.send();
If you are using an old version Browser, then loading the binary can be as follows
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; }
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!