我有一个AJAX请求,我想在返回的AJAX结果中添加更多属性。任何帮助都会很棒
这是我的AJAX请求代码:
var form_data = {};
$.ajax({
type: "GET",
url: "../../../sample_data/chart1.json",
data: form_data,
success: function( response) {
var result = $(data);
console.log(result.datasets.push(style));
var ctx = document.getElementById("chart_div_won").getContext("2d");
var options = {
responsive: true,
maintainAspectRatio: true,
pointDotRadius: 5,
showXLabels: 5,
};
var myLineChart = new Chart(ctx).LineAlt(response, options);
},
error: function() {
$('div#chart-container').html('<div class="notification-body"><p class="notification-heading">Loading error...</p><p class="notification-description">Unfortunatley for some reason visual data failed to load.</p></div>');
},
dataType: "json",
contentType: "application/json; charset=utf-8",
});
返回以下数据:
{
"labels":[
"1 Feb",
"8 Feb",
"15 Feb",
"22 Feb",
"29 Feb",
"7 Mar",
"14 Mar",
"21 Mar",
"28 Mar",
"4 Apr",
"11 Apr",
"18 Apr",
"25 Apr"
],
"datasets":[
{
"data":[
77,
55,
40,
65,
59,
80,
81,
56,
55,
65,
59,
80,
75
]
}
]
}
我的问题是我想在以下(在'data:'级别)添加/推入返回的'数据集'数组:
fillColor:"rgba(253,0,20,0.2)",
strokeColor:"rgba(253,0,20,1)",
pointColor:"#fff",
pointStrokeColor:"rgba(253,0,20,1)",
pointHighlightFill:"#fff",
pointHighlightStroke:"rgba(253,0,20,1)"
这可能吗?如何?
答案 0 :(得分:1)
您有嵌套数组。所以你需要做这样的事情:
for(var i = 0; i < result.datasets.length; i++)
{
for(var j = 0; j < result.datasets[i].data.length; j++)
{
result.datasets[i].data[j]["fillColor"] = "rgba(253,0,20,0.2)";
result.datasets[i].data[j]["strokeColor"] = "rgba(253,0,20,1)";
result.datasets[i].data[j]["pointColor"] = "#fff";
result.datasets[i].data[j]["pointStrokeColor"] = "rgba(253,0,20,1)";
result.datasets[i].data[j]["pointHighlightFill"] = "#fff";
result.datasets[i].data[j]["pointHighlightStroke"] = "rgba(253,0,20,1)";
}
}
答案 1 :(得分:0)
返回的数据成为常规Javascript对象。您可以使用常规分配将属性添加到所需级别:
res.datasets[0].fillColor = "rgba(253,0,20,0.2)";
res.datasets[0].strokeColor = "rgba(253,0,20,1)";
等等。