我試圖把一個XMLHttpRequest到這樣將XMLhttpRequest轉換爲函數失敗:異步或其他?
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的功能。然而我'consistenly failling 得到的結果作爲輸出:
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)
如何使它工作,因此它返回新的數據作爲輸出?
解決方案:我的最終實現是visible here,並JS: how to load a bitmap image and get its base64 code?。
是的,這就是事情的異步工作。手動調用'onload'不會實際加載請求。您可以將回調傳遞給'getImageBase64'並在'onload'中回調,或返回[promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise )。 – Ryan