javascript - 使用php从angularjs中的数据库中获取数据

标签 javascript php angularjs ajax

我是 Angular JS 新手,我想使用 php 从数据库中获取数据。我尝试以下代码。

          <html>
           <head>
              <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script>
   var myApp = angular.module('myApp',[]);
   myApp.controller('studentController', ['$scope','$http', function ($scope,$http) {
                  var url = "ajax.php";
                  $http.get(url).success( function(response) {
                      $scope.students = response;
                      });
               }]);


              </script>
           </head>
           <body>
              <div ng-app = "myApp" ng-controller = "studentController">
                 <table>
                    <tr>
                       <th>Name</th>
                    </tr>

                    <tr ng-repeat = "student in students">
                       <td>{{ student.Name }}</td>
                    </tr>
                 </table>
              </div>
           </body>
        </html>

ajax.php 这段代码给我以下输出:

[{"Name":"Mahesh","Roll":"122222"},{"Name":"ajay","Roll":"444433"}]

但我无法在前端显示...谢谢。

<?php
    $con = mysqli_connect("localhost","root","","adworld");
    $res= mysqli_query($con,"SELECT * FROM students");
    $result = array();
    while($row=mysqli_fetch_assoc($res)){
        $result[] = $row;
    }   
    echo json_encode($result);
?>

最佳答案

工作代码:

<!DOCTYPE html>
<html >
<script src= "angular.js"></script>
<body>

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

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

</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
   $http.get("ajax.php")
   .success(function (response) {$scope.names = response;});
});
</script>

</body>
</html>

ajax.php

<?php
    $conn = new mysqli("localhost","root","","adworld");
    $result = $conn->query("SELECT * FROM students");
    $arr = array();
    while($rs = $result->fetch_assoc()) 
    {
      $arr[] = $rs;
    }

    echo json_encode($arr);
    ?>

关于javascript - 使用php从angularjs中的数据库中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33656042/

相关文章:

javascript - chalice 的 <r :script> tag as compared to <g:javascript>

Javascript 谷歌音译 API 不通过 h​​ttps 提供

php - 连接两个 mysql 表中的列

javascript - 访问当前所选 DOM 元素的子项

php - Magento - 最高价过亿

php - 使用 Laravel 获取从 offset 开始的所有行

angularjs - Paypal 上下文父页面不重定向

javascript - AngularJS ng-repeat 具有多个显示不同值的列表

javascript - 带有 Angularjs 的 sockjs - 错误 : INVALID_STATE_ERR

Javascript 更新数组值(如果存在),否则将新数组推送到对象