2016-02-29 90 views
2

我想創建一個服務,將返回從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"} 

什麼想法?

回答

1

將數據發送到客戶端之前嘗試這個

controller('DistinctMatcode', function($scope, DistinctAPIService){ 
    DistinctAPIService.listDistinct('material', 'matcode').then(function(response){ 
    $scope.data = response.data.data; 
    console.log(JSON.stringify(data)); 
}) 
+0

它刪除'{ 「數據」:'但仍然有另一個'{ 「數據」:',我只想得到的結果爲'[{「表達式1 「:」value「}] –

+0

試試這個$ scope.data = data.data.data –

+0

很好,它的工作 –

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() .'}}'; 
} 

} >

+0

仍然相同。其實hadiJZ已經給出了答案,謝謝 –