我试图从 addEventListener 中的全局函数/变量中获取JSON对象。但我只是将值设为 undefined ,尽管在addEventListener中调用了全局函数。
我应该收到动态创建并存储在变量 colJSON 中的JSON。
function returnJSON() {
var colSize = 7;//hardcoded.
var SegTotal;
var colSTR = '';
var colJSON;
$.ajax({
url: "./myCSV.csv",
type: "GET",
async: true,
dataType: "text",
success: function (csvd) {
data = $.csv.toArrays(csvd);
//data=get(csvd)
SegTotal= data;
var seg= 'Segment';
var strStart= '[';
var strEnd= ']';
var strquote= "'";
var nextline= '\n';
for(
var i= 0; i < SegTotal.length; i++) {
var segstr = seg.concat(i + 1);
var ARvalue = SegTotal[i] / colSize;
var strAR = '';
for (var j = 0; j < colSize; j++) {
//alert('hello');
strAR = strAR.concat(ARvalue).concat(',');
}
colSTR = colSTR.concat(strStart).concat(strquote).concat(segstr).concat(strquote).concat(',').concat(strAR).concat(SegTotal[i]).concat(strEnd).concat(',').concat(nextline);
}
alert(colSTR);
colSTR = strStart.concat(colSTR).concat(strEnd);
//alert("length of csv data - " +SegTotal.length);
alert("JSONstring below\n\n" + colSTR);
//colJSON = JSON.stringify(colSTR);
colJSON= eval('('+ colSTR+ ')');
alert(colJSON);
$('#csvdata').html(colJSON);
}
});
return colJSON;
}
document.addEventListener("DOMContentLoaded", function() {
//var collector=colJSON; //Here is the global variable used
var collector=returnJSON();
alert("collectorJSON check here\n" + collector);
var container = document.getElementById('collectorPortfolio'), hot;
hot = new Handsontable(container, {
data: collector,
rowHeaders: true,
contextMenu: true,
manualColumnResize: true,
colHeaders: ['TYPE', 'Col1', ' Col2', 'Col3' , 'Col4' ,'Col5','Col6','Col7', 'Total'],
formulas: true,
columns: [
{readOnly: true},
{readOnly: false},
{readOnly: false},
{readOnly: false},
{readOnly: false},
{readOnly: false},
{readOnly: false},
{readOnly: false},
{readOnly: true}
],
});
});