0

I got a XMLHttpRequest to read data from a local XLSX file. (I used xlsx.full.min.js)

The file looks like this:

The code i tried looks like this:

/* set up XMLHttpRequest */
var url = "Test.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"});

  /* DO SOMETHING WITH workbook HERE */
  var first_sheet_name = workbook.SheetNames[0];
  /* Get worksheet */
  var worksheet = workbook.Sheets[first_sheet_name];
  var test = XLSX.utils.sheet_to_json(worksheet,{raw:true})
  console.log(test)
}

oReq.send();

console.log(test) //I can not access it here..

It loads the data correctly into an object which looks like this:

My problem now is this:

I can not access the object outside the function. When I try it i get the error: "ReferenceError: test is not defined". How is it possible to make the variables global so it is accessable outside the function?

Thanks for your help :)

House97_
  • 373
  • 1
  • 3
  • 10
  • you can't. (Well, you could declare `var test` in global scope, and assign to in in the Ajax callback: `test = ...` with no `var` - but then you'll find that `test` is undefined when you use it in the global scope.) Just write functions that take this data as a parameter, and call them with the data from within the callback. – Robin Zigmond May 10 '19 at 10:51
  • Could you write an example how its possible? – House97_ May 10 '19 at 11:01
  • basically whatever you want to do with `test` in the global scope, put inside a function, say `function myFunction(test) { /* code goes here */ }`. Then, inside the callback after `var test = ...`, put `myFunction(test)` – Robin Zigmond May 10 '19 at 11:22

0 Answers0