weixin_33705053 2018-03-02 22:02 采纳率: 0%
浏览 42

JSON JQuery和莫里斯图表

I'm trying to use the setData() function for a morris chart but I'm having some problems using json data.

Without setData(), this works perfect...

        if ($('#morris-area-graph').length > 0) {
        var labelColor = $('#morris-area-graph').css('color');
        var Chart = Morris.Area({
            element: 'morris-area-graph',
            behaveLikeLine: true,
            data: [
                {"x":"1:00am","y":"5.5"},{"x":"2:00am","y":"4.2"}

            ],
            xkey: 'x',
            parseTime: false,

            ykeys: ['y'],
            labels: ['Glucose Level'],
            gridTextColor: labelColor,
            lineColors: $('#morris-area-graph').data('colors').split(',')
        });
    }

This doesn't work at all...

        $.ajax({
        type: "GET",
        url: "http://url/jsontest.php",
        success: function (result) {
            console.log(result);

            Chart.setData(result);
        }
    });

    // Morris Area demo
    if ($('#morris-area-graph').length > 0) {
        var labelColor = $('#morris-area-graph').css('color');
        var Chart = Morris.Area({
            element: 'morris-area-graph',
            behaveLikeLine: true,
            data: [
                {"x":"1:00am","y":"5.5"},{"x":"2:00am","y":"4.2"}

            ],
            xkey: 'x',
            parseTime: false,

            ykeys: ['y'],
            labels: ['Glucose Level'],
            gridTextColor: labelColor,
            lineColors: $('#morris-area-graph').data('colors').split(',')
        });
    }

As demonstrated above, taking the string of json that the php file outputs and inserting it into the data : [ ] part of the morris chart, works perfect. However using the setData function, i get undefined points and the graph doesnt display any of the data.

I can have the php file output the json as :

[{"x":"1:00am","y":"5.5"},{"x":"2:00am","y":"4.2"}]

or

{"x":"1:00am","y":"5.5"},{"x":"2:00am","y":"4.2"}

neither appear to work. however the second one works fine if it's in the data : [] statically as a string.

  • 写回答

1条回答 默认 最新

  • weixin_33717298 2018-03-02 22:29
    关注

    jQuery's $.ajax() function doesn't parse JSON strings by default, which is probably the reason why your script is failing.

    So, you either:

    a) parse your JSON response manually:

    $.ajax({
        type: "GET",
        url: "http://url/jsontest.php",
        success: function (result) {
    
            var data = JSON.parse( result );
            console.log(data);
    
            if ( data ) {
                Chart.setData(data);
            }
    
        }
    });
    

    ... or, b) use $.getJSON() instead, which does parse JSON strings automatically:

    $.getJSON(
        "http://url/jsontest.php",
        function (result) {
    
            console.log(result);
            Chart.setData(result);
    
        }
    });
    
    评论

报告相同问题?