使用.ajax读取XML

时间:2017-10-08 14:12:10

标签: javascript xml

我编写了以下代码来从XML文件中读取变量。该变量未传递给Highchart图表,我不确定原因。当我插入数字代替变量时,图表可以正常工作。



    <script>

    $.ajax({
       type: "GET",
       url: "data.xml",
       dataType: "xml",
       success: function(xml) {
         $(xml).find('height').each(function(){
           var johnheight = $(this).find('john').text()
           var mikeheight = $(this).find('mike').text()
         });
       }
    });
    
    $(function () { 
    var myChart = Highcharts.chart('graph', {
        chart: {
            type: 'bar'
        },
        title: {
            text: null
        },
        xAxis: {
        categories: [''],
        },
        yAxis: {
            title: {
                text: null
            }
        },
        series: [{
            name: 'John',
            data: [johnheight]
        }, {
            name: 'Mike',
            data: [mikeheight]
        }]
    });
    });
    </script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

$(function() {})不等待$.ajax()调用,变量仅在.each()内定义。您可以使用$.holdReady()等待$.ajax() success函数并在函数调用之前声明变量,可选地在window或其他对象上声明变量,并在.each()中定义变量

$.holdReady(true);

var johnheight = mikeheight = void 0;

$.ajax({
       type: "GET",
       url: "data.xml",
       dataType: "xml",
       success: function(xml) {
         $(xml).find('height').each(function(){
           johnheight = $(this).find('john').text();
           mikeheight = $(this).find('mike').text();
           return false;
         });
         $.holdReady(false);
       }
    });

$(function () { 
    var myChart = Highcharts.chart('graph', {
        chart: {
            type: 'bar'
        },
        title: {
            text: null
        },
        xAxis: {
        categories: [''],
        },
        yAxis: {
            title: {
                text: null
            }
        },
        series: [{
            name: 'John',
            data: [johnheight]
        }, {
            name: 'Mike',
            data: [mikeheight]
        }]
    });
    });