使用AJAX发出POST请求后,我得到以下JSON响应:
{
"ServiceName": "ABC",
"Response": {
"Object": [
{
"Attributes": {
"Attribute": [
{
"AttributeName": "Name",
"AttributeValue": "XYZ"
},
{
"AttributeName": "Place",
"AttributeValue": "Abc"
},
{
"AttributeName": "Country",
"AttributeValue": "Americas"
},
{
"AttributeName": "Code",
"AttributeValue": "576"
}
]
}
},
{
"Attributes": {
"Attribute": [
{
"AttributeName": "Name",
"AttributeValue": "XYZHJ"
},
{
"AttributeName": "Place",
"AttributeValue": "Abchgh"
},
{
"AttributeName": "Country",
"AttributeValue": "India"
},
{
"AttributeName": "Code",
"AttributeValue": "536"
}
]
}
}
]
}}
我正在使用datatable来显示数据..但是使用这个嵌套的JSON,我无法直接获取数据。 我使用此https://datatables.net/examples/server_side/post.html https://datatables.net/reference/option/ajax.dataSrc作为参考。
答案 0 :(得分:3)
您必须迭代响应并将其转换为dataTables可以理解的格式。当我阅读示例数据时,您有一个Object
保留Attributes
块,其中Attribute
包含密钥=>值对AttributeName
=> AttributeValue
。因此,在dataSrc
回调中解析响应:
var table = $("#example").DataTable({
ajax : {
url : 'nestedData.json',
dataSrc : function(json) {
var temp, item, data = [];
for (var i=0;i<json.Response.Object.length;i++) {
temp = json.Response.Object[i].Attributes.Attribute;
item = {};
for (var elem in temp) {
item[temp[elem].AttributeName] = temp[elem].AttributeValue
}
data.push(item);
}
return data
}
},
columns : [
{ data : 'Name', title : 'Name' },
{ data : 'Place', title : 'Place' },
{ data : 'Country', title : 'Country' },
{ data : 'Code', title : 'Code' }
]
})
dataSrc
回调返回表单上的对象数组:
data = [
{ Code: "576", Country: "Americas", Name: "XYZ", Place: "Abc" },
{ Code: "536", Country: "India", Name: "XYZHJ", Place: "Abchgh" }
]