使用PHP的AngularJS和我想要JSON中的响应

时间:2017-10-09 10:52:49

标签: php angularjs json

我希望JSON中的响应,但是得到了错误的响应。我正在学习AngularJS。请帮帮我。

我正在使用以下fetch.php代码:

<?php
    $servername = "localhost";
    $username = "root";
    $password = "admin";
    $dbname = "ghanshyam";
    // Create connection
    $conn = new mysqli($servername, $username, $password,$dbname );

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 


     $query = "SELECT * FROM `table`"; 
     $result = $conn->query($query);
            if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
           $r[] = $row;
        }
    } else {
        echo "0 results";
    }

    header('Content-Type: application/json');

    echo json_encode(($r));

    $conn->close();
?>

并使用下面的HTML代码

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="comen.js"></script>
<body>
 <div>
     <p>hello</p>
    <table ng-app="myApp" ng-controller="myCtrl" >
        <tr ng-repeat="x in myWelcome track by $index">
            <td> {{ x.one}} </td>
            <td> {{ x.two }} </td>
            <td> {{ x.three }} </td>

        </tr>
    </table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $http.get("fetch.php")
    .success(function(response) {
        console.log(response.data);
        $scope.myWelcome = response.data;
    });
});
</script>
    </body>
</html>

我收到如下所示的回复:

<?php
$servername = "localhost";
$username = "root";
$password = "admin";
$dbname = "ghanshyam";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname );

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 


 $query = "SELECT * FROM `table`"; 
 $result = $conn->query($query);
        if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
       $r[] = $row;
    }
} else {
    echo "0 results";
}

1 个答案:

答案 0 :(得分:1)

从角度版本1.4开始,不推荐使用

.success。因为您使用的是版本1.6,请使用then来捕获响应。

 $http.get("fetch.php")
    .then(function(response) {
        console.log(response.data);
        $scope.myWelcome = response.data;
    });

确保将$r定义为数组。

 $r = array();
 if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $r[] = $row;
    }
 } else {
        echo "0 results";
 }