【问题标题】:I cannot retrieve json data from php with Angular $http.get我无法使用 Angular $http.get 从 php 中检索 json 数据
【发布时间】:2014-11-21 18:29:09
【问题描述】:

这是我的 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 数据?

【问题讨论】:

  • 这是 json 对象,如果您想将其作为字符串提示,您可能需要JSON.stringify(data)。否则,在您的代码中,您应该能够只访问属性(即 data.foo.bar)
  • 问题是我认为 $http.get 不检索 json 数据,出于某种原因,来自 php 脚本。
  • 这就是为什么我有一个解决方案来检查它,如果它没有成功,它将是 null、一个空数组或你的警报中的空对象。另一种简单的检查方法是运行curl http://host:port/path

标签: php json angularjs


【解决方案1】:

$http.get 与 JSON 一起工作正常 我建议你 validate 你的 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

【讨论】:

    【解决方案2】:

    我解决了这个问题。这个产品有问题

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

    【讨论】:

      猜你喜欢
      • 2020-02-28
      • 2018-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 2021-09-16
      相关资源
      最近更新 更多