0

我正在使用 XMLHttpRequest 和 sheetjs ( https://github.com/SheetJS/js-xlsx ) 从 excel 电子表格创建 json 对象。一切都运行良好,除了我正在努力访问外部创建的对象oReq.onload。创建 json 对象后,我想将其用作 XMLHttpRequest 下面更多代码的输入对象。

我已经尝试return json在最后oReq.onload并尝试在其中包含我的附加代码,function (e) {}但两个选项都没有奏效。任何建议,将不胜感激。

    /* set up XMLHttpRequest */
    var url = "graph.xlsx";
    var oReq = new XMLHttpRequest();
    oReq.open("GET", url, true);
    oReq.responseType = "arraybuffer";

    oReq.onload = function(e) {
      var arraybuffer = oReq.response;

      /* convert data to binary string */
      var data = new Uint8Array(arraybuffer);
      var arr = new Array();
      for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
      var bstr = arr.join("");

      /* Call XLSX */
      var workbook = XLSX.read(bstr, {type:"binary"});

      /* Create the json object */
      var json = to_json(workbook); 

      /*Converts excel format to JSON*/
      function to_json(workbook) {
        var result = {};
        workbook.SheetNames.forEach(function(sheetName) {
            var roa = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
            if(roa.length > 0){
                result[sheetName] = roa;
            }
        });
        return result;
      }
    };
    oReq.send();

    /*I WOULD LIKE TO USE THE CREATED JSON OBJECT HERE*/
4

3 回答 3

0

正如@epascarello 所建议的那样,最终成为一个异步问题。可以在帖子中找到一个非常全面的解释:为什么我的变量在我在函数内部修改后没有改变?- 异步代码参考

于 2016-08-10T11:03:26.183 回答
0

使用回调,您可以在函数外部获取数据,如此处所述https://stackoverflow.com/a/23667087/7981344

function asyncReq(callback){ 
oReq.onload = function(e) {

  var arraybuffer = oReq.response;

  var data = new Uint8Array(arraybuffer);
  var arr = new Array();
  for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
  var bstr = arr.join("");

  var workbook = XLSX.read(bstr, {
    type: "binary"
  });

  var sheet_name = workbook.SheetNames[0];
  var worksheet = workbook.Sheets[sheet_name];
  myJson = XLSX.utils.sheet_to_json(worksheet, {
    header: 1
  });
callback(myJson);
}
}

oReq.send();
asyncReq(function(result){
   //do whatever you want now with the output data
console.log(result);
于 2017-05-10T17:45:42.623 回答
-1

希望这还不算太晚,但我遇到了同样的问题。只需设置一个超时,然后等待 onload 函数像这样完成

setTimeout(function() {
  console.log (yourvariable); //prints the variable outside the function
}, 1000);
于 2017-05-10T15:50:59.243 回答