XMLHttpRequest:在oReq.onload

时间:2016-08-09 12:43:34

标签: javascript ajax xmlhttprequest js-xlsx

我正在使用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*/

3 个答案:

答案 0 :(得分:0)

根据@epascarello的建议,结束了异步问题。可以在帖子中找到非常全面的解释:Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

答案 1 :(得分: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);

答案 2 :(得分:-1)

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

setTimeout(function() {
  console.log (yourvariable); //prints the variable outside the function
}, 1000);