gpt4 book ai didi

php - AngularJS 链接到数据库

转载 作者:搜寻专家 更新时间:2023-10-31 21:59:41 26 4
gpt4 key购买 nike

索引.php

<!doctype html>
<html ng-app="rjtApp">
<head>
<title>PHP MySQL API Consumed with AngularJS</title>
<script src="angular.min.js"></script>
<script src="data.js"></script>
</head>

<body>
<div ng-controller="GetUsers">

<table>
<thead><tr><th>Name</th></tr></thead>
<tbody>
<tr ng-repeat="user in users"><td>{{ user.name }}</td></tr>
</tbody>
</tfoot></tfoot>
</table>

</div>
</body>

</html>

api.php(这个连接我测试没问题。)

<?php

// set up the connection variables
$db_name = 'air';
$hostname = '127.0.0.1';
$username = 'root';
$password = '123456';

// connect to the database
$dbh = new PDO("mysql:host=$hostname;dbname=$db_name", $username, $password);

// a query get all the records from the users table
$sql = 'SELECT USER_NAME FROM air_users LIMIT 1';

// use prepared statements, even if not strictly required is good practice
$stmt = $dbh->prepare( $sql );

// execute the query
$stmt->execute();

// fetch the results into an array
$result = $stmt->fetch( PDO::FETCH_ASSOC );

// convert to json
$json = json_encode( $result );

// echo the json string
echo $json;
?>

数据.js

alert("this is connect");

var app = angular.module("rjtApp", []);

app.controller("GetUsers", function($scope, $http)

{

function getProject(){

$http.get("api.php").success(function(data){

$scope.projects = data; //the data are stored in projects

});

};

});

getProject();

我的目的是进行实时验证以检查已退出的数据库名称,但我什至不知道如何将 AngularJS 连接到数据库,我做错了什么?

最佳答案

您正在从 Controller 外部调用 getProject,因此它在外面是未定义的(它在 Controller 本地)。所以把那个电话移到里面:

alert("this is connect");

var app = angular.module("rjtApp", []);

app.controller("GetUsers", function($scope, $http)

{

function getProject() {

$http.get("api.php").success(function(data) {

$scope.projects = data; //the data are stored in projects

});

};
getProject(); // moved this line

});

然后,$http 服务应该运行。从技术上讲,您应该使用 GET 请求,但它仍将以与 POST 相同的方式工作。我想指出的是,您目前没有在页面的任何地方使用 projects - 因此您只会在网络控制台中看到数据。

关于php - AngularJS 链接到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30795268/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com