簡體   English   中英

我無法使用Angular $ http.get從php檢索json數據

[英]I cannot retrieve json data from php with Angular $http.get

這是我的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();
}


?>

這是我的控制器

  function ProductListCtrl($http)
{

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

}

警報消息是[object Object,...],如何從php檢索json數據?

$ http.get與JSON配合良好我建議您驗證 json並再次測試我使用$ http和ng-repeat為您創建了一個簡單示例

<!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

我解決了這個問題。這個產品錯了

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




   }

}());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM