javascript - 使用 Angular JS 从运行 MySQL 的 PHP 服务器获取数据时出错

标签 javascript php mysql angularjs internal-server-error

当我的 Angular 应用程序调用我的 php 文件时,我收到 [$http:baddata] 错误。 我不确定错误的确切触发位置,但我相信这是构建 json 对象的问题!我附上了所有相关代码。任何帮助都会很棒。提前致谢:)

enter image description here

Angular 文档显示了这一点 enter image description here

这是连接到我的数据库并尝试将 JSON 格式字符串返回给调用文件的 PHP 文件

<?php 
echo '<script>console.log("Inside php file!")</script>';
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

require_once('mysqli_connect.php');

$query = "SELECT rideid, destination, price, capacity, userid, origin, departDate, vehicle FROM rides";

$result = @mysqli_query($dbc, $query);

$outp = "";
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
     if ($outp != "") {$outp .= ",";}
    $outp .= '{"Origin":"'  . $rs["origin"] . '",';
    $outp .= '"Destination":"'   . $rs["destination"]        . '",';
    $outp .= '"Price":"'. $rs["price"]     . '"}';
    $outp .= '"Capacity":"'. $rs["capacity"]     . '"}';
}

$outp ='{"records":['.$outp.']}';
//echo '<script>console.log(JSON.stringify('.$outp.'))</script>';
$conn->close();

echo($outp);

这是向 PHP 文件发出请求的 Angular 应用

<html>
<head>
    <!-- Include Angular -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
</head>
<body>

<!-- Ride Table -->
     <div ng-app = "rideAppTest" ng-controller= "rideCtrlTest">
        <table>
          <tr ng-repeat = "x in names">
            <td>{{x.Origin}}</td>
            <td>{{x.Destination}}</td>
            <td>{{x.Price}}</td>
            <td>{{x.Capacity}}</td>
          </tr>
        </table>
     </div>
<!-- End Ride Table -->

<!--Ride Table Script-->
<script>
  var app = angular.module('rideAppTest', []);
  app.controller('rideCtrlTest', function($scope, $http) {
    $http.get("angularFilter.php")
    .then(
      function (response) {
        $scope.names = response.data.records;
      },
      function(data){
        console.log("Error!" + data);
      }

        );
});
</script>
</body>
</html>

最佳答案

不要像现在这样构造 JSON,首先收集数组或对象中的所有内容,然后执行 echo json_encode($result);

像这样:

$outp = [];
while($rs = $result->fetch_array(MYSQLI_ASSOC)) {
    $outp[] = $rs;
}
echo json_encode(["records" => $outp]);

关于javascript - 使用 Angular JS 从运行 MySQL 的 PHP 服务器获取数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46506866/

相关文章:

javascript - 使用带路由的 ngUpgrade 引导 Angular 2 rc.6 混合应用程序

javascript - 如何在 ElasticSearch 和 ElasticSearch Javascript 客户端中按 ID 和 ID 查找

php - 使用 PHP 从(搜索引擎)引用网址获取关键字

php - 如何使用 phpDocumentor、教程/扩展文档编写代码块?

mysql - REST API、OAuth2 和身份验证错误

javascript - 特定 div 元素的 onclick 事件处理程序

javascript - 脚本内文本框中使用的日期选择器

php - 如何在 Highchart 中显示此 MySQL 循环?

phpmyadmin 挂起并且只导入大约 50% 的数据库?

php - 执行多个查询然后输出为数组