我正在尝试创建一个服务,它将从php api返回一个json数据,但不是返回纯json数据,而是似乎将JSON与其配置一起返回。
services.js
.service('DistinctAPIService', function($http){
var base = 'http://localhost/onseral/api/';
this.listDistinct = function(table, field){
return $http({
method: 'POST',
url: base + '/listDistinct.php',
params: {
table: table,
field: field
}
});
}
})
.controller('DistinctMatcode', function($scope, DistinctAPIService){
DistinctAPIService.listDistinct('material', 'matcode').then(function(data){
$scope.data = data;
console.log(JSON.stringify(data));
})
})
listdistinct.php
<?php
require_once '/config/dbconfig.php';
$table = $_GET['table'];
$field = $_GET['field'];
GetData($table,$field);
function GetData($tablename,$fieldname) {
$sql = "SELECT DISTINCT $fieldname as expr1 FROM $tablename order by expr1 asc";
try {
$db = getdb();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode(array('data' => $data));
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
?>
而不是返回正确的JSON数据,它返回
{"data":{"data":[{"expr1":"CFFBPS16"}]},"status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"url":"http://localhost/onseral/api//listDistinct.php","params":{"table":"material_copy","field":"matcode"},"headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK"}
任何想法?
答案 0 :(得分:1)
试试这个
controller('DistinctMatcode', function($scope, DistinctAPIService){
DistinctAPIService.listDistinct('material', 'matcode').then(function(response){
$scope.data = response.data.data;
console.log(JSON.stringify(data));
})
答案 1 :(得分:0)
在向客户端发送数据之前使用标头功能。 我修改了 listdistinct.php 文件。尝试一下,如果问题仍然存在,请告诉我。
<?php $sql = "SELECT DISTINCT $fieldname as expr1 FROM $tablename order by expr1 asc";
try {
$db = getdb();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
header('Content-Type: application/json');
echo json_encode(array('data' => $data));
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
} ?&GT;