在javascript里如何使变量调用ajax中的值

MoonzzZ
  • 2
新手上路,请多包涵

我构造了一个画图表的javascript,想通过ajax从后端获取x和y的值,然后构造出图标。但是结果图是空的,也就是ajax中返回的值,给不到图的变量中。想问下应该如何解决?代码如下:

<script type="text/javascript">
$(document).ready(function(e) {
    var bar_labels = null,
        bar_data = null,
        line_labels = null,
        line_data = null;
        $.ajax(
        {
            url: "http://0.0.0.0:5900/get_index_chart_data",//ajax请求的路径
            type: 'POST',
            headers    :{'Content-Type': 'application/json'},
            data: JSON.stringify({}),//这边是参数   你后端需要接受参数
            success: function (received_data) {//这边是ajax成功后返回的数据 字符串

                bar_labels = received_data["bar_label"];
                bar_data = received_data["bar_data"];
                line_labels = received_data["line_label"];
                line_data = received_data["line_data"];
            }
        }
    );

    var $dashChartBarsCnt  = jQuery( '.js-chartjs-bars' )[0].getContext( '2d' ),
        $dashChartLinesCnt = jQuery( '.js-chartjs-lines' )[0].getContext( '2d' );

    var $dashChartBarsData = {
        labels: bar_labels,
        datasets: [
            {
                label: '注册用户',
                borderWidth: 1,
                borderColor: 'rgba(0,0,0,0)',
                backgroundColor: 'rgba(51,202,185,0.5)',
                hoverBackgroundColor: "rgba(51,202,185,0.7)",
                hoverBorderColor: "rgba(0,0,0,0)",
                data: bar_data
            }
        ]
    };
    var $dashChartLinesData = {
        labels: line_labels,
        datasets: [
            {
                label: '交易资金',
                data: line_data,
                borderColor: '#358ed7',
                backgroundColor: 'rgba(53, 142, 215, 0.175)',
                borderWidth: 1,
                fill: false,
                lineTension: 0.5
            }
        ]
    };
    console.log($dashChartLinesData);

    new Chart($dashChartBarsCnt, {
        type: 'bar',
        data: $dashChartBarsData
    });
    
    var myLineChart = new Chart($dashChartLinesCnt, {
        type: 'line',
        data: $dashChartLinesData
    });
});
</script>

然后后端就是一个简单的函数

@app.route('/get_index_chart_data', methods=['POST'])
def load_data():

'''
加载index页面对应的两张表的数据
:return:
'''
print("get request")
data = {}
data["bar_label"] = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
data["bar_data"] = [2500, 1500, 1200, 3200, 4800, 3500, 1500]

data["line_label"] = ['2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014']
data["line_data"] = [20, 25, 40, 30, 45, 40, 55, 40, 48, 40, 42, 50]

return jsonify(data)

求解答,谢谢!!!!!

回复
阅读 2.2k
2 个回答

试下把图表的初始表放到异步请求结果里

<script type="text/javascript">
$(document).ready(function(e) {
    var bar_labels = null,
        bar_data = null,
        line_labels = null,
        line_data = null;
        $.ajax(
        {
            url: "http://0.0.0.0:5900/get_index_chart_data",//ajax请求的路径
            type: 'POST',
            headers    :{'Content-Type': 'application/json'},
            data: JSON.stringify({}),//这边是参数   你后端需要接受参数
            success: function (received_data) {//这边是ajax成功后返回的数据 字符串

                bar_labels = received_data["bar_label"];
                bar_data = received_data["bar_data"];
                line_labels = received_data["line_label"];
                line_data = received_data["line_data"];
                
                var $dashChartBarsCnt  = jQuery( '.js-chartjs-bars' )[0].getContext( '2d' ),
        $dashChartLinesCnt = jQuery( '.js-chartjs-lines' )[0].getContext( '2d' );

                var $dashChartBarsData = {
                    labels: bar_labels,
                    datasets: [
                        {
                            label: '注册用户',
                            borderWidth: 1,
                            borderColor: 'rgba(0,0,0,0)',
                            backgroundColor: 'rgba(51,202,185,0.5)',
                            hoverBackgroundColor: "rgba(51,202,185,0.7)",
                            hoverBorderColor: "rgba(0,0,0,0)",
                            data: bar_data
                        }
                    ]
                };
                var $dashChartLinesData = {
                    labels: line_labels,
                    datasets: [
                        {
                            label: '交易资金',
                            data: line_data,
                            borderColor: '#358ed7',
                            backgroundColor: 'rgba(53, 142, 215, 0.175)',
                            borderWidth: 1,
                            fill: false,
                            lineTension: 0.5
                        }
                    ]
                };
                console.log($dashChartLinesData);

                new Chart($dashChartBarsCnt, {
                    type: 'bar',
                    data: $dashChartBarsData
                });

                var myLineChart = new Chart($dashChartLinesCnt, {
                    type: 'line',
                    data: $dashChartLinesData
                });
                
            }
        }
    );

});
</script>

ajax是异步的,不阻塞代码执行。

当请求发出之后,ajax()后面的代码继续执行,当需要用到变量的时候,请求还没回来;
当success中的拿到请求的数据后,下面赋值的代码已经执行过了。

所以如果需要用到请求的数据,要把数据的操作,放到success函数中。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏