2014-11-21 139 views
0

這我的PHP代碼

<?php 


try { 
    $dbcon=new PDO('mysql:host=localhost;dbname=angular;charset=utf8',"root",""); 

    $dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $dbcon->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'"); 
    $query="SELECT * FROM products "; 
    $sql=$dbcon->prepare($query); 
    $sql->execute(); 
    $result=$sql->fetchAll(PDO::FETCH_OBJ); 

    $json_result=json_encode($result); 

    echo $json_result; 

}catch(PDOException $e) { 
    echo 'ERROR: ' . $e->getMessage(); 
} 


?> 

和此我的控制器從PHP檢索JSON數據到角

function ProductListCtrl($http) 
{ 

    $http.get('api/products.php').success(function (data) { alert(data); this.product = data; }); 

} 

警報消息是[對象的對象,.. 。],我如何檢索從PHP的JSON數據?

+2

如果你想將它作爲提醒你可能想'JSON.stringify(數據)'一個字符串,它是JSON對象。否則,在你的代碼中,你應該只能訪問屬性(即data.foo.bar) – nerdwaller 2014-11-21 18:31:09

+0

問題是我認爲'$ http.get'不能檢索json數據,出於某種原因從php腳本。 – user1658429 2014-11-21 18:48:33

+0

這就是爲什麼我有一個解決方案來檢查,如果它沒有成功,它將是空的,一個空數組或空警告對象。另一種簡單的檢查方法是運行'curl http:// host:port/path' – nerdwaller 2014-11-21 20:31:24

回答

0

$ http.get做工精細用JSON 我建議你再validate您的JSON和測試 我創建了一個簡單的例子,你用$ HTTP和NG-重複

<!doctype html> 
<html ng-app="test"> 
    <head> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script> 
    <script> 
     var app = angular.module('test', []); 
     app.controller('test', function($scope, $http) { 
     $http.get('test.json').success(function(data){ 
      console.log(data); 
      $scope.items = data; 
     }); 
     }); 
    </script> 
    </head> 
    <body ng-controller="test"> 
    <div ng-repeat="item in items">{{item.name}}</div> 
    </body> 
</html> 

和JSON文件

[{ 
    "name":"name1" 
}, 
{ 
    "name":"name2" 
}] 

,也是一個鏈接看直播的Plunker http://plnkr.co/edit/MN6UPg1ba1OYNFNHKMdG?p=preview

0

我解決了problem.The錯誤是this.product

(function() 
{ 
    "use strict"; 
    var app = angular.module('ProductList'); 
    app.controller('ProductListCtrl',['$scope','$http', ProductListCtrl]); 

    function ProductListCtrl($scope, $http) { 

     $http.get('api/products.php').success(function (data) { $scope.product = data; }); 




    } 

}());