如何从编码 JSON 的 PHP 页面获取数据


How to fetch data from a PHP page that encodes JSON?

请帮帮我。我已经想了几个小时如何解决这个问题,但我仍然不知道如何。><</p>

这是我的 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"}]

但是,我不知道如何将这些数据获取/传输到我的服务.js控制器.js。

这是我的服务.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;
  }
})

这是我的控制器.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(的文件时使用上述格式,它会给我数组对象。

为此要访问 Js 文件中的数据,您必须使用 ajax。在需要数据时调用 Ajax。

有关更多详细信息,请参阅以下链接。

http://www.w3schools.com/php/php_ajax_database.asp

尝试:

$http.get('resources/json/jsonfile.php',{ responseType : 'json' })