【问题标题】:How can have variable data be from a url in javascript如何让变量数据来自 javascript 中的 url
【发布时间】:2020-08-09 01:28:57
【问题描述】:

我正在使用 chart.js 制作图表,但文档显示了集成到 html 中的数据。我想从外部源获取数据,例如 localhost:80/data。如何让 var barChartData 成为来自 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]
            }]

        };

网址会返回这个

{
        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]
        }]

    }

【问题讨论】:

    标签: javascript variables url chart.js


    【解决方案1】:

    你需要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
    }
    

    【讨论】:

    • 它在 JSON 数据的第 2 行第 5 列显示:SyntaxError: JSON.parse: expected property name or '}'
    • JSON 数据到底是什么样的?你的例子不是有效的 JSON
    • 我通过用双引号替换单引号并将引号放在其他位置来修复它。
    【解决方案2】:

    你可以使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-04
      • 2012-11-03
      • 2017-03-13
      相关资源
      最近更新 更多