这是我的问题:datatable插件只接受我相信的数组,但我的API返回一个带有数组的对象。我想弄清楚我是否需要提取这些信息(如何?)或者插件是否有一些方法可以帮助我(有一个):
//the datatable plugin expects the following JSON structure
[
{
"ID":"a5f415a7-3d4f-11e5-b52f-b82a72d52c35",
"Record":1,
"HostName":"SRX552P"
}
]
//my PHP server returns the following JSON structure:
{
"status":"success",
"message":"data retrieved",
"data":[
{
"ID":"a5f415a7-3d4f-11e5-b52f-b82a72d52c35",
"Record":1,
"HostName":"SRX552P"
}
]
}
var allData = null;
//this is my angularjs service where I am grabbing all the 'data':
function getAllData() {
dataservice.get('table001').then(function(data){
allData = data;
});
return allData;
}
//it looks like my issue is exactly what this post describes:
http://stackoverflow.com/questions/27797435/accessing-json-data-in-angularjs-datatables-using-dtoptions
//but applying ".withDataProp('data.data')" didn't work for me:
...
this.standardOptions = DTOptionsBuilder
.fromFnPromise(getAllData())
.withDataProp('data.data')
//.fromSource('api/tables/datatables.standard.json') //static data works fine!
//Add Bootstrap compatibility
.withDOM("<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs'l>r>" +
"t" +
"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>")
.withBootstrap();
this.standardColumns = [
DTColumnBuilder.newColumn('ID'),
DTColumnBuilder.newColumn('Record'),
DTColumnBuilder.newColumn('HostName')
];
...
//this is the service
(function () {
'use strict';
angular.module('app.ipxtool').factory('dataservice', dataservice);
dataservice.$inject = ['$http', '$q'];
function dataservice($http, $q) {
var serviceBase = 'api/v1/';
var obj = {};
obj.get = function (q) {
return $http.get(serviceBase + q).then(success).catch(fail);
};
function success(results) {
if (results.data.status == "error") {
logger.error(results.data.message, '', 'Error'); //$response["data"] = null for errors;
}
if (results.data.status == "warning") {
logger.warning(results.data.message, '', 'Warning');
}
if (results.data.status == "success") {
logger.success(results.data.message, results.data.data, 'Success'); //$response["data"] = $rows;
}
return results.data;
}
function fail(e) {
return (e);
}
return obj;
};
})();
使用Fiddler我可以看到返回的所有数据。我也输出第一个数组项,如下所示:
console.log("var allData: " + "[" + JSON.stringify(alldata.data[1]) + "]");
此问题的解决方案是添加以下内容:
.fromFnPromise(function() {
return dataservice.get('table001');
})
不知道为什么调用getAllData()
不起作用。所以最后我解决了这个问题。谢谢。
你可以在php页面本身的输出变量的开头和结尾添加[
和]
,这样它就会返回一个合适的JSON
输出。由于我在Angular
之前也遇到过这样的问题,因为它不接受直接的Object输入,我使用上面的方法将它转换成完整的JSON
。
还要在PHP页面顶部添加以下代码:
header('Content-Type: application/json');
这样,它将返回JSON格式文本中的内容。