2015-11-21 68 views
0

connect.phpJSON數據連接到SQL

<?php 
    $host  = "host=127.0.0.1"; 
    $port  = "port=5432"; 
    $dbname  = "dbname=Northwind"; 
    $credentials = "user=postgres password=qwer1234"; 

    $db = pg_connect("$host $port $dbname $credentials" ); 

    $sql =<<<EOF 
     SELECT * from customers; 
EOF; 

    $ret = pg_query($db, $sql); 
    if(!$ret){ 
     echo pg_last_error($db); 
     exit; 
    } 
    $rows = array(); 
    while($r = pg_fetch_assoc($ret)){ 
     $rows[] = $r; 
     echo json_encode($rows); 
    } 
?> 

JSON

[{"CustomerID":"ALFKI","CompanyName":"Alfreds Futterkiste","ContactName":"Maria Anders","ContactTitle":"Sales Representative","Address":"Obere Str. 57","City":"Berlin","Region":null,"PostalCode":"12209","Country":"Germany","Phone":"030-0074321","Fax":"030-0076545"}][{"CustomerID":"ALFKI","CompanyName":"Alfreds Futterkiste","ContactName":"Maria Anders","ContactTitle":"Sales Representative","Address":"Obere Str. 57","City":"Berlin","Region":null,"PostalCode":"12209"........... 

AngularJs.html

<html ng-app="myApp"> 
<head> 
    <title></title> 
    <meta charset="utf-8" /> 
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> 
    <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> 
</head> 
<body> 
    <div ng-controller="customersCtrl"> 
     <div> 
      <table class="table table-striped"> 
       <thead> 
        <tr> 
         <th>CustomerID</th> 
         <th>CompanyName</th> 
         <th>ContactName</th> 
        </tr> 
       </thead> 
       <tbody> 
        <tr ng-repeat="item in customers"> 
         <td>{{item.CustomerID}}</td> 
         <td>{{item.CompanyName}}</td> 
         <td>{{item.ContactName}}</td> 
        </tr> 
       </tbody> 
      </table> 
     </div> 
    </div> 
</html> 
<script> 

var app = angular.module("myApp", []); 

app.controller('customersCtrl', ['$scope', '$http', function($scope,$http) { 
    console.log("Initiating the controller"); 
    $http.get('http://localhost:8080/connect.php').success(function(data) { 
    $scope.customers = data; 
    }); 
}]); 
</script> 

這樣做的結果是什麼也不顯示上angularjs.html幫助我!感謝名單。

+0

嘗試從.get和'$ scope.customers'中檢索'console.log()'數據來檢查結果是如何分配的 – Tristan

+0

XMLHttpRequest無法加載http:// localhost:8080/connect.php。請求的資源上沒有「Access-Control-Allow-Origin」標題。因此不允許原產地'null'訪問。 – ooz

+0

謝謝添加代碼標題(「Access-Control-Allow-Origin:*」); header(「Content-Type:application/json; charset = UTF-8」);完成。 – ooz

回答

0

啓動控制器

的XMLHttpRequest不能加載http://localhost:8080/connect.php。請求的資源上沒有「Access-Control-Allow-Origin」標題。因此不允許原產地'null'訪問。