0

I'm trying to use a json response as the tooltipValueLookups parameter in a sparklines graph, without success. The tooltip just keeps showing 0:5 and 1:8 instead of Mulder:5 and Scully:8

It works perfectly if I just declare the variable agents with the exactly same json:

var agents = {"names":{"0":"Mulder", "1":"Scully"}}

But evrything goes south when I try to do it with the server response, as intended. Could anyone tell me please, what am I doing wrong?

var agents = $.ajax({
    url     : "/ajaxAgents",
    type    : "get",
    dataType: 'json'
});

Response: {"names":{"0":"Mulder", "1":"Scully"}}

$("#mini-chart").sparkline([5,8], {
    type: 'bar',
    height: '30px',
    barWidth: 6,
    barSpacing: 2,
    barColor: '#0aa699',
    tooltipFormat: '<span style="color: {{color}}">&#9679;</span> {{offset:offset}}: {{value}}',
    tooltipValueLookups:{offset:agents.names},
    negBarColor: '#0aa699'});

Thanks in advance.

EDIT

After a lot of coffee and swearing, I finally got it to work. Not a very elegant solution, I must admit.

First, I had to change the server-side php function to return a string, rather than json.

Then in the ajax call:

var response = $.ajax({
    url     : "/ajaxAgents",
    type    : "get",
    dataType: 'text',
    global  : false,
    async   : false,
    success : function(data){return data;}
}).responseText;

Then, parse the response and filter it:

var agents = $.parseJSON(response);
var filteredNames = $.map(agents.names, function(el) {
        return el;
    });

And finally, the sparklines function:

    $("#mini-chart").sparkline(agentsData, {
    type: 'bar',
    height: '30px',
    barWidth: 6,
    barSpacing: 2,
    barColor: '#0aa699',
    tooltipFormat: '<span style="color: {{color}}">&#9679;</span> {{offset:offset}}: {{value}}',
    tooltipValueLookups:{offset:filteredNames},
    negBarColor: '#0aa699'});

@Hüseyin: Thanks for your assistance, it was very helpful.

4

1 回答 1

1

使用$.grep过滤 json

var filteredNames = $.map(agents.names, function(el, i) {
    return el;
});

并在您的功能中使用,例如;

tooltipValueLookups:{offset: filteredNames}

你可以在这里看到演示:jsfiddle

注意:如果你从服务器返回字符串,你需要使用;

var agents = jQuery.parseJSON(response);
于 2014-03-28T21:05:52.780 回答