AngularJS,PHP MySQL实现返回PHP代码而不是查询结果

时间:2018-12-28 02:46:04

标签: php angularjs

我能够使用PHP从数据库读取值。然后,我试图通过AngularJS控制器执行此PHP。

view1.js

angular.module('myApp.view1', ['ngRoute'])

.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/view1', {
        templateUrl: 'view1/view1.html',
        controller: 'View1Ctrl'
    });
}])

.controller('View1Ctrl', ['$scope', '$http', function ($scope, $http) {
    $http.get('view1/view1.php').then(successCallback, errorCallback);

    function successCallback(response) {
        $scope.songs = response.data;
    }

    function errorCallback(error) {
        alert(error);
    }
}]);

view1.php

<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "songs"; /* Database name */

$con = mysqli_connect($host, $user, $password, $dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

$sel = mysqli_query($con, "select * from description");
$data = array();

while ($row = mysqli_fetch_array($sel)) {
    $data[] = array("artist" => $row['artist'], "key" => 
$row['song_key'], "beat" => $row['beat']);
}

echo json_encode($data);

view1.html

<div ng-app="myApp.view1" ng-controller="View1Ctrl">
    {{songs}}
</div>

这是我完成的代码,它不返回db数据。它返回与{{songs}}完全相同的PHP代码。

1 个答案:

答案 0 :(得分:0)

这可能是因为您要从默认的npm服务器(端口8000)请求PHP服务器(端口80),然后尝试将get()请求参数更改为:

$http.get('http://localhost/view1/view1.php').then(successCallback, errorCallback);  

因此它将不会通过npm服务器。