Turn XMLhttpRequest into a function fails: asynchronity or other?

后端 未结 2 2077
不知归路
不知归路 2021-01-17 03:46

I try to turn an XMLHttpRequest into a function such

var getImageBase64 = function (url) { // code function
    var xhr = new XMLHttpRequest(url); 
    ...          


        
2条回答
  •  不思量自难忘°
    2021-01-17 04:19

    When you use xhr.onload your actually defining a function for JS to call when it loads, hence the value of xhr.onload is the function not the output of the function. Returning xhr.onload() will call that function and return the output, but your onload function has no return statement and hence no output. Additionally you are calling xhr.onload synchronously as you set up the object, and hence it won't have any data to process.

    I suggest you add a callback parameter to your function like so, this will execute when the data has loaded.

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

    Then you would use it like so

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

提交回复
热议问题