2014-03-28 18 views
0

我試圖使用json響應作爲tooltipValueLookups參數在sparklines圖中,沒有成功。工具提示只是不斷出現0:5和1:8,而不是穆德:5和Scully:8Json響應作爲工具提示值查找jQuery的迷你圖

它完美,如果我只是完全相同的JSON聲明變量代理

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

但是,當我試圖按照服務器響應來做到這一點時,evrything就會朝南。任何人都可以告訴我,我做錯了什麼?

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

響應:{ 「名稱」:{ 「0」: 「穆德」, 「1」: 「斯卡利」}}

$("#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'}); 

預先感謝。

編輯

大量的咖啡和宣誓就職後,我終於得到它的工作。我不得不承認,這不是一個很好的解決方案。

首先,我不得不改變服務器端的php函數返回字符串,而不是json。

然後在Ajax調用:

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

然後,解析響應並將其過濾:

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

最後,迷你圖功能:

$("#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'}); 

@侯賽因:感謝您的幫助,這非常有幫助。

回答

1

過濾JSON與$.grep

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

而在你的功能使用等;

tooltipValueLookups:{offset: filteredNames} 

你可以看到演示的位置:jsfiddle

注:如果要返回從服務器字符串,則需要使用;

var agents = jQuery.parseJSON(response); 
+0

對不起,它不起作用。我無法重新聲明json,它是來自服務器的響應。另外,我很確定** tooltipValueLookups **選項**必須**具有密鑰。就像我說的,如果我直接聲明JSON對象,funcion就像魅力一樣。當我嘗試使用響應時,情況出錯,這與預期完全相同。謝謝,無論如何:) – Sam

+0

@Sam,好的JSON可以保持相同。我已更新我的代碼和演示,請參閱我的更新版本。 –

+0

這使我瘋狂。 parseJSON返回null,這是有道理的,因爲json已經是一個對象。映射agent.names引發TypeError。再次感謝您的回覆,@Hüseyin。 – Sam