2016-11-26 136 views
0

我正在w3schools上嘗試以下AngularJS教程。AngularJS:從php腳本獲取JSON

Link to w3schools tutorial

我改劇本,使之與我的PHP腳本的工作之一:

<!DOCTYPE html> 
<html > 
<style> 
table, th , td { 
    border: 1px solid grey; 
    border-collapse: collapse; 
    padding: 5px; 
} 
table tr:nth-child(odd) { 
    background-color: #f1f1f1; 
} 
table tr:nth-child(even) { 
    background-color: #ffffff; 
} 
</style> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
<body> 

<div ng-app="myApp" ng-controller="customersCtrl"> 

<table> 
    <tr ng-repeat="x in names"> 
    <td>{{ x.name }}</td> 
    </tr> 
</table> 

</div> 

<script> 
var app = angular.module('myApp', []); 
app.controller('customersCtrl', function($scope, $http) { 
     $http.get("http://wirtschaftsinformatik.web2page.ch/selectModule.php") 
//my url 
     .then(function (response) {$scope.names = response.data.records;}); 
    }); 
    </script> 

    </body> 
    </html> 

這實際上是行不通的。我猜它是因爲php文件,這裏是代碼:

<?PHP 
    //Verbindung zur Datenbank 
    include "inc_mysql.php"; 

    //SQL-String 
    $select = "SELECT * FROM module ORDER BY name ASC"; 

    // Codierung 
    mysql_set_charset("utf8"); 

    //SQL-Befehl in Variable speichern 
    $sql = mysql_query($select); 

    //Array erstellen 
    $jsonArray = array(); 

    while ($row = mysql_fetch_array($sql)){ 
     $jsonArray[] = $row; 
    } 

    echo json_encode($jsonArray, JSON_UNESCAPED_UNICODE); 
?> 

你知道缺少什麼嗎?

這裏是JSON輸出

[{"0":"12","id":"12","1":"Betriebsbuchhaltung","name":"Betriebsbuchhaltung","2":"2016-10-19 15:44:16","timestamp":"2016-10-19 15:44:16"},{"0":"13","id":"13","1":"Datenbanken","name":"Datenbanken","2":"2016-10-28 20:35:49","timestamp":"2016-10-28 20:35:49"},{"0":"6","id":"6","1":"Logistik","name":"Logistik","2":"0000-00-00 00:00:00","timestamp":"0000-00-00 00:00:00"},{"0":"14","id":"14","1":"Statistik","name":"Statistik","2":"2016-11-02 15:13:13","timestamp":"2016-11-02 15:13:13"},{"0":"1","id":"1","1":"System Engineering","name":"System Engineering","2":"0000-00-00 00:00:00","timestamp":"0000-00-00 00:00:00"}] 
+0

什麼不起作用?表不顯示記錄? – Sajeetharan

+0

是的,表格不顯示記錄。 –

+0

你可以發佈json – Sajeetharan

回答

1

返回的JSON沒有記錄的財產,這裏有一個簡單的解決方案:

echo json_encode(["records"=>$jsonArray], JSON_UNESCAPED_UNICODE); 
+0

謝謝,但仍有東西仍然失蹤,因爲它仍然不工作。我創建一個新文件: http://wirtschaftsinformatik.web2page.ch/test.php –

+0

我的不好,它的工作原理!非常感謝你! –

1

HTML

<div ng-controller="listController"> 
    <table> 
     <tr> 
     <th>Id</th> 
     <th>Name</th> 
     <th>Time</th> 
     </tr> 
     <tr ng-repeat="person in names"> 
     <td>{{person.id}}</td> 
     <td>{{person.name}}</td> 
     <td>{{person.timestamp}}</td> 
     </tr> 
    </table> 
    </div> 

DEMO

+0

非常感謝!它的作品很棒!我看到你創建了一個JSON文件。沒有辦法從php腳本直接獲取它?我是 –

+0

是的,你可以使用get http調用並執行相同的操作。標記爲答案,如果有幫助 – Sajeetharan

+0

謝謝!你的意思是?我把http://wirtschaftsinformatik.web2page.ch/selectModule.php但它沒有工作。 –