問題描述
我嘗試將 XMLHttpRequest 變成這樣的函數
I try to turn an XMLHttpRequest into a function such
var getImageBase64 = function (url) { // code function
var xhr = new XMLHttpRequest(url);
... // code to load file
... // code to convert data to base64
return wanted_result; // return result of conversion
}
var newData = getImageBase64('http://fiddle.jshell.net/img/logo.png'); // function call
doSomethingWithData($("#hook"), newData); // reinjecting newData in wanted place.
我已成功加載文件并轉換為 base64.然而,我一直未能將結果作為輸出:
I'am successful to load the file, and to convert to base64. I'am however consistenly failling to get the result as an output :
var getImageBase64 = function (url) {
// 1. Loading file from url:
var xhr = new XMLHttpRequest(url);
xhr.open('GET', url, true); // url is the url of a PNG image.
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) { // 2. When loaded, do:
console.log("1:Response?> " + this.response); // print-check xhr response
var imgBase64 = converterEngine(this.response); // converter
}
}
xhr.send();
return xhr.onload(); // <fails> to get imgBase64 value as the function's result.
}
console.log("4>>> " + getImageBase64('http://fiddle.jshell.net/img/logo.png') ) // THIS SHOULD PRINT THE BASE64 CODE (returned resukt of the function getImageBase64)
請參閱小提琴.
See Fiddle here.
如何使其工作,以便將新數據作為輸出返回?
解決方案:我的最終實現是在此處可見,然后繼續JS:如何加載位圖圖像并獲取其base64代碼?.
Solution: my final implementation is visible here, and on JS: how to load a bitmap image and get its base64 code?.
推薦答案
JavaScript 中的異步調用(如 xhr)無法像常規函數那樣返回值.編寫異步函數時常用的模式是這樣的:
Asynchronous calls in JavaScript (like xhr) can't return values like regular functions. The common pattern used when writing asynchronous functions is this:
function asyncFunc(param1, param2, callback) {
var result = doSomething();
callback(result);
}
asyncFunc('foo', 'bar', function(result) {
// result is what you want
});
所以您的翻譯示例如下所示:
So your example translated looks like this:
var getImageBase64 = function (url, callback) {
var xhr = new XMLHttpRequest(url);
... // code to load file
... // code to convert data to base64
callback(wanted_result);
}
getImageBase64('http://fiddle.jshell.net/img/logo.png', function(newData) {
doSomethingWithData($("#hook"), newData);
});
這篇關于將 XMLhttpRequest 變成函數失敗:異步還是其他?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!