我的JavaScript代码有问题。我正在尝试使用动态图表,该图表将在使用plotly.reshape函数更改选择字段时进行更新。我在chart()函数内部调用了一个基于Ajax请求的函数,我希望它等待变量分配,然后绘制一个图表。我认为我在错误的地方使用了异步/等待。你们可以帮我吗?这是我的第一个js脚本,但是我在项目中需要它。
function chart(){
var x = Chart();
var X =x[0];
var Close=x[1];
var High=x[2];
var Low=x[3];
var Open=x[4];
console.log(X);
var trace1 = {
x: X,
close: Close,
decreasing: {line: {color: '#7F7F7F'}},
high: High,
increasing: {line: {color: '#17BECF'}},
line: {color: 'rgba(31,119,180,1)'},
low: Low,
open: Open,
type: 'ohlc',
xaxis: 'x',
yaxis: 'y'
};
var data = [trace1];
var layout = {
...
};
Plotly.newPlot('chart', data, layout);
}
function Chart(){
var data, date = [], price = [], open=[], Timestamp=[], High=[], Low = [];
let selectedItem = document.getElementById('currency-selector').value;
var url = `http://127.0.0.1:8000/${selectedItem}/`;
var x = new Array()
var requestURL = url; //URL of the JSON data
var request = new XMLHttpRequest({mozSystem: true}); // create http request
request.onreadystatechange = async function() {
if(request.readyState == 4 && request.status == 200) {
data = JSON.parse(request.responseText);
for (var i=0; i<data.length;i++) {
date.push(data[i].date)
price.push(data[i].close);
High.push(data[i].high);
open.push(data[i].Open);
Low.push(data[i].low);
}
//chart(date,price,High,Low,open);
}
await request.open('GET', requestURL, true);
request.send(); // send the request
}
return [date,price,High,Low,open];
}
由于设置原因,我无法对此进行测试,但这应该可行...并按照您期望的顺序返回内容。
这是使用fetch api,它通常比xmlhttp request api干净得多。
但是,您知道,异步是包含等待功能的标签。和.then()是如何在回调中对事物进行排序的方式...等待的值将在返回等待的值之前先执行。
async function Chart(){
let date = [], price = [], open=[], Timestamp=[], High=[], Low = [];
let selectedItem = document.getElementById('currency-selector').value;
let url = `http://127.0.0.1:8000/${selectedItem}/`;
let requestURL = url; //URL of the JSON data
return await fetch(requestURL)
.then(res=>res.json())
.then(data=>{
data.forEach(x=>{
date.push(x.date)
price.push(x.close);
High.push(x.high);
open.push(x.Open);
Low.push(x.low);
})
})
.then(()=>{
return [date,price,High,Low,open];
})
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句