使用angularjs

时间:2016-06-09 19:24:46

标签: php mysql angularjs json

我从mysql db中获取数据并将其放入json格式。

fetch.php文件:

enter image description here

echo $ json;将以下内容输出到控制台。

[{"id":"1","emp_no":"1111","first_name":"1fname","last_name":"1lname","dept_name":"1dept"},{"id":"2","emp_no":"2222","first_name":"2fname","last_name":"2lname","dept_name":"2dept"},{"id":"3","emp_no":"3333","first_name":"3fname","last_name":"3lname","dept_name":"3dept"},{"id":"4","emp_no":"4444","first_name":"4fname","last_name":"4lname","dept_name":"4dept"},{"id":"5","emp_no":"5555","first_name":"5fname","last_name":"5lname","dept_name":"5dept"},{"id":"6","emp_no":"6666","first_name":"6fname","last_name":"6lname","dept_name":"6dept"},{"id":"7","emp_no":"7777","first_name":"7fname","last_name":"7lname","dept_name":"7dept"},{"id":"8","emp_no":"8888","first_name":"8fname","last_name":"8lname","dept_name":"8dept"},{"id":"9","emp_no":"9999","first_name":"9fname","last_name":"9lname","dept_name":"9dept"}]

我的控制器看起来像这样:

.controller('fetchController', function ($scope, $http) {
$http.get("fetch.php")
    .success(function (data) {
        $scope.user = data;
        console.log($scope.user);
    });

$ scope.user = data.data;有人建议这样做但我在console.log($ scope.user);

时得到一个未定义的

$ scope.user = data;的console.log($ scope.user);显示与上面相同的json输出。

enter image description here

然后我想把它放到我的html表中:

<table>
<tr>
    <th>ID</th>
    <th>Number</th>
    <th>First</th>
    <th>Last</th>
    <th>Depart</th>
</tr>
<tr ng-repeat="x in user track by $index">
    <td>{{x.id}}</td>
    <td>{{x.emp_no}}</td>
    <td>{{x.first_name}}</td>
    <td>{{x.last_name}}</td>
    <td>{{x.dept_name}}</td>
</tr>

但我没有将数据返回到我的页面...当我对一些json数据进行硬编码时返回数据,但是当从PHP查询中读取时则不返回。有什么想法吗?

.controller('fetchController', function ($scope, $http) {
    $http.get("fetch.php")
        .success(function (data) {
            $scope.user = [{
                "id": "1",
                "emp_no": "1111",
                "first_name": "1fname",
                "last_name": "1lname",
                "dept_name": "1dept"
            }, {
                "id": "2",
                "emp_no": "2222",
                "first_name": "2fname",
                "last_name": "2lname",
                "dept_name": "2dept"
            }];
            console.log($scope.user);
        });

返回:

page when json hardcoded

编辑:我已经在帖子中添加了更多细节,所以希望有人可以看到问题所在。

1 个答案:

答案 0 :(得分:2)

问题是你的“连接到db”输出。您必须从PHP文件中删除该行,其余的应该按预期工作。

echo $json看起来很好,因为它是有效的json,但由于你之前在PHP脚本中输出了文本,因此Angular中的JSON解码正在破坏。如果查看从控制台发布的输出,您会在应用程序中看到前缀为JSON的“connected to db”文本。该文本前缀强制PHP的输出无效。