請幫幫我吧。我一直在想如何解決這個問題幾個小時,但我仍然不知道如何。 > <如何從編碼JSON的PHP頁面獲取數據?
這是我的php頁面,它以JSON格式顯示值。
jsonfile.php:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","online_evaluation_revised") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from tblaccount";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
?>
它顯示是這樣的:
[{"account_id":"89","username":"2012100014","password":"25d55ad283aa400af464c76d713c07ad"},{"account_id":"90","username":"2012102400","password":"25d55ad283aa400af464c76d713c07ad"},{"account_id":"91","username":"2012101087","password":"25d55ad283aa400af464c76d713c07ad"},{"account_id":"92","username":"2011102090","password":"25d55ad283aa400af464c76d713c07ad"}]
不過,我不如何獲取/這些數據傳輸到我的services.js和controller.js 。
這裏是我的services.js:
app.service("myService", function($http,$q)
{
var deferred = $q.defer();
$http.get('resources/json/jsonfile.php').then(function(data)
{
deferred.resolve(data);
});
this.getAccounts = function()
{
return deferred.promise;
}
})
這裏是我的controller.js:
.controller("myCtrl",function($scope,myService)
{
var promise = myService.getAccounts();
promise.then(function (data)
{
$scope.allAccounts = data;
var accounts = data;
console.log($scope.allAccounts);
});
})
每當我使用使用上述格式的數據,它給我的是這樣的控制檯日誌:
Object {data: "<?php
↵ //open connection to mysql db
↵ $con…db connection
↵ mysqli_close($connection);
↵?>", status: 200, config: Object, statusText: "OK"}
奇怪,因爲如果我使用JSON格式讀取文件時,上面的格式(不PHP),它給了我數組對象。
這是行不通的。 T_T – soshixsnsd
你可以console.log你的Ajax響應嗎? (函數(data) {console.log(data); });'$ http.get('resources/json/jsonfile.php')。 –