如何让变量数据来自javascript中的url



我使用chart.js制作图表,但文档显示了集成到html中的数据。我想从外部源获取数据,例如localhost:80/data。如何将varbarChartData作为url中的数据?

var barChartData = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Dataset 1',
backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
borderColor: window.chartColors.red,
borderWidth: 1,
data: [1,2,3]
}, {
label: 'Dataset 2',
backgroundColor: color(window.chartColors.blue).alpha(0.5).rgbString(),
borderColor: window.chartColors.blue,
borderWidth: 1,
data: [4,5,6]
}]
};

url将返回此

{
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Dataset 1',
backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
borderColor: window.chartColors.red,
borderWidth: 1,
data: [1,2,3]
}, {
label: 'Dataset 2',
backgroundColor: color(window.chartColors.blue).alpha(0.5).rgbString(),
borderColor: window.chartColors.blue,
borderWidth: 1,
data: [4,5,6]
}]
}

您需要fetch()url中的数据,然后将其传递到图表:

fetch('http://localhost:80/data') // Get the data from the url
.then(response => response.json()) // Parse the response into json
.then(data => {
// The json from the url, use it to create the chart
console.log(data);
})
.catch(e => {
// Catch errors
console.log(e);
});

例如,如果您有一个名为createChart()的函数,您可以像这样传递数据:

// Replace the console.log(data) in the then() with the function
.then(createChart)
function createChart(data) {
// Create chart here with json data
}

您可以使用Fetch

var barChartData = fetch('localhost:80/data')
.then(function(response){
return response.json();
})
.catch(err){
//deal with error
}

//deal with response you can render it with a for loop

最新更新