等待 Ajax 请求绘制图表

我遇到了 javascript 代码的问题。我正在尝试动态图表,它将在使用 plotly.reshape 函数更改选择字段时更新。我在 chart() 函数中调用基于 Ajax 请求的函数,我希望它等待变量分配,然后绘制图表。我想我在错误的地方使用了 async/await。你们能帮帮我吗?这是我的第一个 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];

  }


蛊毒传说
浏览 102回答 1
1回答

qq_花开花谢_0

由于设置的原因,我无法对此进行测试,但这应该可以工作……并按照您期望的顺序返回东西。这是使用 fetch api,它通常比 xmlhttp 请求 api 干净得多。但是你知道,async 是包含 await 的函数的标签。.then() 是如何在这样的回调中排序的……等待的值将在返回等待的值之前首先执行。&nbsp;async function Chart(){&nbsp; let date = [], price = [], open=[], Timestamp=[], High=[], Low = [];&nbsp; let selectedItem = document.getElementById('currency-selector').value;&nbsp; let url = `http://127.0.0.1:8000/${selectedItem}/`;&nbsp;&nbsp; let requestURL = url; //URL of the JSON data&nbsp; &nbsp; return await fetch(requestURL)&nbsp; &nbsp; .then(res=>res.json())&nbsp; &nbsp; .then(data=>{&nbsp; &nbsp; &nbsp; &nbsp;data.forEach(x=>{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;date.push(x.date)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;price.push(x.close);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;High.push(x.high);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;open.push(x.Open);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Low.push(x.low);&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp;})&nbsp; &nbsp;.then(()=>{&nbsp; &nbsp; &nbsp; return [date,price,High,Low,open];&nbsp; &nbsp; })&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript