Search code examples
javascriptxmlhttprequesthttpresponse

How to return a JSON in GET method?


Based on xlsx github documentation, i made this function to return a json object. This is a method i tried:

function getData(){
    var data; 
    var url = "Book1.xlsx";
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.responseType = "arraybuffer";

    req.onload = function(e) {
        var data = new Uint8Array(req.response);
        var wb = XLSX.read(data, {type:"array"});

        var ws = wb.Sheets['Sheet1'];
        data = XLSX.utils.sheet_to_json(ws);
        //console.log(data);
    }
    //return data;
    req.send();
}

My question is how can i return data so that i'll be able to use it in my other function? My problem is i have a lot of XMLHttpRequest() just to read my Book1.xlsx. Hope someone can help.


Solution

  • function getData(cb){
        var data; 
        var url = "Book1.xlsx";
        var req = new XMLHttpRequest();
        req.open("GET", url, true);
        req.responseType = "arraybuffer";
    
        req.onload = function(e) {
            var data = new Uint8Array(req.response);
            var wb = XLSX.read(data, {type:"array"});
    
            var ws = wb.Sheets['Sheet1'];
            data = XLSX.utils.sheet_to_json(ws);
            cb(data)
            //console.log(data);
        }
        //return data;
        req.send();
    }
    
    const d = new Promise(resolve =>
        getData(resolve)
    ) 
    
    d.then(data => { 
        console.log(data) 
    })