将XMLhttpRequest转换为函数失败:异步还是其他?

时间:2014-07-24 16:47:11

标签: javascript jquery xmlhttprequest blob

我尝试将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。然而,我仍然坚持将结果作为输出

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)

请参阅 Fiddle here

如何使其工作,以便将新数据作为输出返回?


解决方案:我的最终实施是visible hereJS: how to load a bitmap image and get its base64 code?

2 个答案:

答案 0 :(得分:1)

JavaScript中的异步调用(如xhr)无法像常规函数一样返回值。编写异步函数时使用的通用模式是:

function asyncFunc(param1, param2, callback) {
  var result = doSomething();
  callback(result);
}

asyncFunc('foo', 'bar', function(result) {
  // result is what you want
});

所以翻译的示例如下所示:

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);
});

答案 1 :(得分:1)

当你使用xhr.onload实际定义一个函数供JS加载时调用,因此xhr.onload的值不是函数的输出函数。返回xhr.onload()将调用该函数并返回输出,但是你的onload函数没有return语句,因此没有输出。此外,您在设置对象时同步调用xhr.onload,因此无法处理任何数据。

我建议你像这样在你的函数中添加一个回调参数,这将在数据加载时执行。

function getImageBase64( url, callback) {
    // 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.callback = callback;
    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
            this.callback(imgBase64);//execute callback function with data
        }
    }
    xhr.send();
}

然后你会像这样使用它

var myCallBack = function(data){
    alert(data);
};
getImageBase64('http://fiddle.jshell.net/img/logo.png', myCallBack);