[英]How can I add to an AJAX array result
I have an AJAX request where I want to add more properties to the returned AJAX result. 我有一个AJAX请求,我想在其中向返回的AJAX结果添加更多属性。 Any help would be great 任何帮助都会很棒
Here is my AJAX request code: 这是我的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",
});
Which returns the following data: 它返回以下数据:
{
"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
]
}
]
}
My question is I want to add/push into the returned 'datasets' array the following (at 'data:' level): 我的问题是我想将以下内容(在“数据:”级别)添加/推入返回的“数据集”数组中:
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)"
Is this possible and how? 这有可能吗?
You have nested arrays. 您有嵌套数组。 So you need to do something like this: 因此,您需要执行以下操作:
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)";
}
}
The returned data becomes a regular Javascript object. 返回的数据成为常规Javascript对象。 You can add properties to the desired level with regular assignments: 您可以使用常规分配将属性添加到所需级别:
res.datasets[0].fillColor = "rgba(253,0,20,0.2)";
res.datasets[0].strokeColor = "rgba(253,0,20,1)";
and so on. 等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.