过去,我使用以下方法适当地解析json数据,因此可以填充选择框:
var request = null;
request = $.ajax({
type: "POST",
url: "url goes here",
dataType: 'text',
success: function(returned) {
returned = JSON.parse(returned)
$.each(returned, function(selectid, item) {
var sel = $("#" + selectid).get(0);
sel.options.length = 0;
$.each(item, function(i, subitem) {
sel.options[i] = new Option(subitem.text, subitem.value);
});
});
request = null;
}
});
我如何将相同的技术应用于下面的代码,但是没有选择框,只需将json解析为drawChart函数?
$.ajax({
url: 'chart_json.aspx',
type: 'POST',
dataType: 'text',
success: function(data) {
drawChart(data);
}
});
我认为您的问题出在您的ajax响应中,我将执行以下操作:
您的回应:
{
graphData : [
['user1',{v:0.00, f:'0.00'}],
['user2',{v:0.00, f:'0.00'}],
['user3',{v:0.00, f:'0.00'}],
['user4',{v:0.00, f:'0.00'}],
['user5',{v:0.00, f:'0.00'}]
],
status : "ok"
}
在您的js中:
$.ajax({
url: 'get_json.aspx',
type: 'POST',
dataType: 'json',//this is important
success: function(data) {
//this is not vital, but it's nice to check the response
if(typeof data === "object" && data.status === "ok"){
graphData = data.graphData;
drawVisualization(graphData);
}
}
});
希望这会有所帮助,思南。
$.ajax({
url: 'get_json.aspx',
type: 'POST',
dataType: 'json', // as noted by Sinan
success: function(data) {
drawVisualization(data);
}
});
function drawVisualization(serverData) {
var chartData = [];
for(var i = 0; i < serverData.length; i++) {
chartData.push([serverData[i][0], serverData[i][1].v]);
}
var data = new google.visualization.DataTable();
data.addColumn('string', 'WIP');
data.addColumn('number', 'Percentage');
data.addRows(chartData);
new google.visualization.PieChart(document.getElementById('visualization')).draw(data, {width: 400, height: 240, is3D:true});
}
chartData数组需要具有2列(因为您在google.visualization.DataTable上两次调用addColumn),每行都有一个字符串和一个数字。
示例here