我在json数据上执行任务。我想在本地上传文件,并希望将其数据分配给全局变量,以便我可以在其他函数中使用该数据。
<!DOCTYPE html>
<head>
<!-- Plotly.js -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<style>
#result {
display:block;
width:400px;
height:200px;
}
#import {
margin:10px 0;
}
</style>
</head>
<body>
<div id="myDiv" style="width: 900px; height: 602px;"><!-- Plotly chart will be drawn inside this DIV --></div>
<input type="file" id="selectFiles" value="Import" /><br />
<button id="import">Import</button>
<textarea id="result">
</textarea>
<script>
//for uploading json file
document.getElementById('import').onclick = function() {
var files = document.getElementById('selectFiles').files;
console.log(files);
if (files.length <= 0) {
return false;
}
var fr = new FileReader();
fr.onload = function(e) {
console.log(e);
var result = JSON.parse(e.target.result);
var formatted = JSON.stringify(result, null, 2);
document.getElementById('result').value = formatted;
}
fr.readAsText(files.item(0));
};
想要将直接JSON数据分配给文本,或者在上面的函数中将stringify分配给全局的abz var。这样我就可以将var用于进一步的功能
var text = ''
var abz1 = JSON.parse(text);
var abz = JSON.stringify(abz1);
var rt1 = []
var in1 = []
var rt2 = []
var in2 = []
var rt3 = []
var in3 = []
var a = abz.groups[0].peaks[0].eic.rt
var b = abz.groups[0].peaks[1].eic.rt
var c = abz.groups[0].peaks[2].eic.rt
//console.log(abz.groups[0].peaks[0].eic.rt)
//console.log(abz.groups[0].peaks[0].eic.intensity)
// a.push(abz.groups[0].peaks[0].eic.rt)
// b.push(abz.groups[0].peaks[0].eic.intensity)
//console.log(a)
// console.log(b)
for (i=0;i < a.length;i++){
rt1.push(abz.groups[0].peaks[0].eic.rt[i])
in1.push(abz.groups[0].peaks[0].eic.intensity[i])
}
for (i=0;i < b.length;i++){
rt2.push(abz.groups[0].peaks[1].eic.rt[i])
in2.push(abz.groups[0].peaks[1].eic.intensity[i])
}
for (i=0;i < c.length;i++){
rt3.push(abz.groups[0].peaks[2].eic.rt[i])
in3.push(abz.groups[0].peaks[2].eic.intensity[i])
}
var trace1 = {
x: rt1,
y: in1,
mode: 'markers'
};
var trace2 = {
x: rt2,
y: in2,
mode: 'markers'
};
var trace3 = {
x: rt3,
y: in3,
mode: 'markers'
};
var data = [ trace1, trace2, trace3 ];
var layout = {
title:'Intensity vs Retension Time - Scatter Plot',
height: 600,
width: 1200
};
Plotly.newPlot('myDiv', data, layout);
</script>
</body>
答案 0 :(得分:1)
我不清楚你的问题是什么,或者你的代码中有什么不起作用。
但我猜你可能有一个回调问题。加载文件的进程需要几毫秒才能使用加载的文件数据调用指定的onload
方法。因此,在调用fr.readAsText();
方法之前将调用onload
之后列出的语句。总之:您希望在加载数据之前使用它们。因此,诀窍是将所有进一步的数据操作放入onload
回调方法。
fr.onload = function(e) {//this is a callback method that will be called, if the file is loaded
console.log(e);
var result = JSON.parse(e.target.result);
//put here your plot code or call a function for using the result variable!!!
//e.g.:
var a = result.groups[0].peaks[0].eic.rt
}
fr.readAsText(files.item(0));//this starts the loading process. Needs some milliseconds. and then it calls asynschrously the before specified onLoad-method
console.log("this output will be made BEFORE the file was loaded, cause the FileReader answers asynchron");
随意提出进一步的问题。