Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从html页面访问javascript获取中的函数_Javascript_Html - Fatal编程技术网

如何从html页面访问javascript获取中的函数

如何从html页面访问javascript获取中的函数,javascript,html,Javascript,Html,我试图使一个网站显示一个基于一些用户上传的json文件的图形。 我使用fetch从servlet中获取JSON数据,并在fetch中创建图形,这很好。只有我想使用addData()函数向同一绘图添加额外数据。问题是我无法访问fetch请求之外的数据,如果addData()函数位于javascript文件的fetch中,我也无法从html页面访问它。 有没有解决这个问题的好方法 我的JavaScript代码: fetch('/json_storage') .then((response)

我试图使一个网站显示一个基于一些用户上传的json文件的图形。 我使用fetch从servlet中获取JSON数据,并在fetch中创建图形,这很好。只有我想使用addData()函数向同一绘图添加额外数据。问题是我无法访问fetch请求之外的数据,如果addData()函数位于javascript文件的fetch中,我也无法从html页面访问它。 有没有解决这个问题的好方法

我的JavaScript代码:


fetch('/json_storage')
    .then((response) => {
        return response.json();
    })
    .then((myJson) => {
        let hrdata = myJson[0].heartRate;
        let timestamp = hrdata.map(t => { return t.timestamp });

        let bpm = hrdata.map( b => {return b.bpm});


        let ctx = document.getElementById('canvas').getContext('2d');
        let canvas = new Chart(ctx, {
            type: 'line',
            data: {
                labels: timestamp,
                datasets: [{
                    label: new Date(timestamp[0]),
                    data: bpm,
                    backgroundColor: 'rgba(255,0,55,0.25)',
                    pointRadius: 0
                }]
            },
            options: {
                title: {
                    display: true,
                    text: 'The course of your heart rate during the day'
                },
                scales: {
                    xAxes: [{
                        type: 'time',
                        time: {
                            unit: 'hour'
                        }
                    }]
                }
            }
        });

        function addData() {
            for (let i =1; i < myJson.length; i++){
                let hrdata = myJson[i].heartRate;
                let bpm = hrdata.map( b => {return b.bpm});
                let timestamp = hrdata.map(t => { return t.timestamp });

                canvas.data.data = bpm;
                canvas.data.labels = timestamp;

                canvas.update();

            }
        }

    });



获取('/json_存储')
。然后((响应)=>{
返回response.json();
})
。然后((myJson)=>{
设hrdata=myJson[0]。心率;
让timestamp=hrdata.map(t=>{return t.timestamp});
让bpm=hrdata.map(b=>{return b.bpm});
设ctx=document.getElementById('canvas').getContext('2d');
让画布=新图表(ctx{
键入:“行”,
数据:{
标签:时间戳,
数据集:[{
标签:新日期(时间戳[0]),
数据来源:bpm,
背景颜色:“rgba(255,0,55,0.25)”,
点半径:0
}]
},
选项:{
标题:{
显示:对,
文字:“一天中的心率变化”
},
比例:{
xAxes:[{
键入:“时间”,
时间:{
单位:小时
}
}]
}
}
});
函数addData(){
for(设i=1;i{return b.bpm});
让timestamp=hrdata.map(t=>{return t.timestamp});
canvas.data.data=bpm;
canvas.data.labels=时间戳;
canvas.update();
}
}
});
和我的HTML代码:

<button id="addData">Add dataset</button>
<canvas id="canvas" width="300" height="300"></canvas>
添加数据集

在您的代码中,
addData
myJson
的作用域在promise回调内部,而promise回调在外部不可用-您需要将它们公开到全局上下文中,或者编写一个可重用函数来公开(返回)
addData

我将fetch函数修改为一个可重用类,在这个类中,您可以从其上下文访问所有数据

类折线图{
构造函数(ctx、dataUrl、initialData=[]){
this.ctx=ctx;
this.data=初始数据;
this.dataUrl=dataUrl;
this.canvas=null;
这是fetchData();
}
fetchData=()=>fetch(this.dataUrl)
。然后((响应)=>{
返回response.json();
})
。然后((myJson)=>{
this.data=myJson;
这个.draw();
返回此.data;
});
绘图=()=>{
如果(!this.ctx){
返回false;
}
设hrdata=this.data[0]。心率;
让timestamp=hrdata.map(t=>{
返回t.timestamp
});
让bpm=hrdata.map(b=>{
返回b.bpm
});
this.canvas=新图表(this.ctx{
键入:“行”,
数据:{
标签:时间戳,
数据集:[{
标签:新日期(时间戳[0]),
数据来源:bpm,
背景颜色:“rgba(255,0,55,0.25)”,
点半径:0
}]
},
选项:{
标题:{
显示:对,
文字:“一天中的心率变化”
},
比例:{
xAxes:[{
键入:“时间”,
时间:{
单位:小时
}
}]
}
}
});
}
addData=()=>{
警报(`in addData函数${JSON.stringify(this.data)}`);
for(设i=1;i{
返回b.bpm
});
让timestamp=hrdata.map(t=>{
返回t.timestamp
});
this.canvas.data.data=bpm;
this.canvas.data.labels=时间戳;
this.canvas.update();
}
}
}
//用法
常数图=新折线图(
document.getElementById('canvas').getContext('2d'),
“/json_存储”
);
document.getElementById('addData')。onclick=chart.addData
添加数据集

要执行所需操作,需要将迄今为止构建的数据存储在页面中持久的数据结构中。如果您正在使用诸如
React
Angular
之类的UI框架,则可以将其存储为状态的一部分,然后当有人单击“添加数据”按钮时,调用函数相应地修改该状态数据并重新呈现结果

另一种方法是重新获取数据并将其与添加的数据组合,但这样会丢失以前添加的任何数据

如果您没有使用UI框架,您是否尝试过将获取的数据保存在javascript文件顶部定义的变量中?获取后,在该变量中设置它,并使用一个单独生成图表的函数。每次单击“添加数据”按钮时,应首先将数据添加到以前保存的数据中,然后根据新数据集重新呈现图表

您需要将数据的存储和
canvas
与数据的处理分开,以便在添加新数据时,可以更新
canvas
,但这超出了您要问的问题的范围,但类似的方法可能是可行的:

const allJson = [];
const ctx = document.getElementById("canvas").getContext("2d");
const canvas = new Chart(ctx, {
  type: "line",
  data: {
    labels: timestamp,
    datasets: [
      {
        label: new Date(timestamp[0]),
        data: bpm,
        backgroundColor: "rgba(255,0,55,0.25)",
        pointRadius: 0
      }
    ]
  },
  options: {
    title: {
      display: true,
      text: "The course of your heart rate during the day"
    },
    scales: {
      xAxes: [
        {
          type: "time",
          time: {
            unit: "hour"
          }
        }
      ]
    }
  }
});

fetch("/json_storage")
  .then(response => response.json())
  .then(myJson => {
    addData(myJson[0]);
  });

function addData(newJson) {
  allJson.push(newJson);
  let bpm = [];
  let timestamp = [];
  for (let i = 0; i < allJson.length; i++) {
    let hrdata = myJson[i].heartRate;
    bpm = bpm.concat(hrdata.map(b => b.bpm));
    timestamp = timestamp.concat(hrdata.map(t => t.timestamp));
  }

  canvas.data.data = bpm;
  canvas.data.labels = timestamp;

  canvas.update();
}
const allJson=[];
const ctx=document.getElementById(“画布”).getContext(“2d”);
const canvas=新图表(ctx{
键入:“行”,
数据:{
标签:时间戳,
数据集:[
{
标签:新日期(时间戳[0]),
数据来源:bpm,
背景颜色:“rgba(