使用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" } ] } } ] }}
我正在使用数据表来显示数据..但是使用此嵌套的JSON,我无法直接获取数据。我正在使用此https://datatables.net/examples/server_side/post.html https://datatables.net/reference/option/ajax.dataSrc作为参考。
您必须遍历响应并将其转换为dataTables可以理解的格式。当我读取样本数据时,您拥有一个包含with键=>值对as => 的Object保存块。因此,在回调中解析响应:Attributes``Attribute``AttributeName``AttributeValue``dataSrc
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回调返回窗体上对象的数组:
dataSrc
data = [ { Code: "576", Country: "Americas", Name: "XYZ", Place: "Abc" }, { Code: "536", Country: "India", Name: "XYZHJ", Place: "Abchgh" } ]