异步加载Google图表?

时间:2013-10-02 19:58:42

标签: jquery asynchronous google-visualization

我有以下代码来加载Google Chart:

function drawChart1() {
        var jsonData1 = $.ajax({
        url: "library/json_netsales.php",
        dataType:"json",
        async: false
    }).responseText;

    // Create our data table out of JSON data loaded from server.
    var data1 = new google.visualization.DataTable(jsonData1);
    var formatter = new google.visualization.NumberFormat(
        {negativeParens: true, pattern: '$###,###'});
    formatter.format(data1, 1);

    // Instantiate and draw our chart, passing in some options.
    var chart1 = new google.visualization.AreaChart(document.getElementById('chart_netsales'));
    chart1.draw(data1, {width: 300, height: '100%', hAxis: { textPosition: 'none', baselineColor: '#fff' }, vAxis: { textPosition: 'none', baselineColor: '#fff', gridlines: {count: 0}, minValue: 0}, chartArea:{width:"100%",height:"80%"}, legend: {position: 'none' }, backgroundColor: '#232323', colors: ['#fff']});
}

现在问题是async标志已经关闭意味着我得到了页面锁定。我想以异步方式加载它,但是我试图让它工作失败了。

我认为将所有内容移动到.responseText到成功处理程序并删除async:false行会使这个工作正常,但我错了。

有关如何异步加载Google Chart的任何想法吗?

1 个答案:

答案 0 :(得分:9)

这应该有效:

function drawChart1() {
    $.ajax({
        url: "library/json_netsales.php",
        dataType: "json",
        success: function (json) {
            // Create our data table out of JSON data loaded from server.
            var data1 = new google.visualization.DataTable(json);
            var formatter = new google.visualization.NumberFormat({
                negativeParens: true,
                pattern: '$###,###'
            });
            formatter.format(data1, 1);

            // Instantiate and draw our chart, passing in some options.
            var chart1 = new google.visualization.AreaChart(document.getElementById('chart_netsales'));
            chart1.draw(data1, {
                width: 300,
                height: '100%',
                hAxis: {
                    textPosition: 'none',
                    baselineColor: '#fff'
                },
                vAxis: {
                    textPosition: 'none',
                    baselineColor: '#fff',
                    gridlines: {count: 0},
                    minValue: 0
                },
                chartArea: {
                    width:"100%",
                    height:"80%"
                },
                legend: {position: 'none'},
                backgroundColor: '#232323',
                colors: ['#fff']
            });
        }
    });
}