我能够使用 PHP 从数据库中读取值。然后我尝试通过AngularJS控制器执行这个PHP。
视图1.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);
}
}]);
视图1.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);
视图1.html
<div ng-app="myApp.view1" ng-controller="View1Ctrl">
{{songs}}
</div>
这是我完成的代码,它返回的不是数据库数据。它为 {{songs}}
返回完全相同的 PHP 代码。
这可能是因为您正在从默认的 npm 服务器(端口 8000)请求 PHP 服务器(端口 80),请尝试get()
将请求参数更改为:
$http.get('http://localhost/view1/view1.php').then(successCallback, errorCallback);
所以它不会通过 npm 服务器。