我正在尝试在AngularJS中创建一个简单的搜索引擎。我的客户端与服务器之间的通信存在问题。我正在尝试遵循w3schools指南http://www.w3schools.com/angular/angular_sql.asp。
这是home.php正文:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
</tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("server.php")
.then(function (response) {$scope.names = JSON.parse(response.data.records);});
});
</script>
这里是server.php:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
error_reporting(2);
$conn = new PDO('mysql:host=localhost;dbname=mygaloo;charset=utf8', 'root', '');
$result = $conn->query("SELECT * FROM associations");
$outp = "";
while($donnees = $query->fetch())
{
if ($outp != "") {$outp .= ",";}
$outp .= '{"Name":"' . $donnees["nom"] . '"}';
}
$outp ='{"records":['.$outp.']}';
$conn->close();
echo($outp);
?>
然而,我得到了这个错误: angular.js:12520SyntaxError:位于0的JSON中的意外标记u ,有什么想法吗?
答案 0 :(得分:0)
这是你的角度代码
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("server.php")
.then(function (response) {
$scope.names = response.data;
}).then(function(response){
console.log(response)
})
});
</script>
这是你的PHP代码。希望它会对你有所帮助。
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', '');
$result = $conn->query("SELECT * FROM associations");
$outp = [];
while($rs = $result->fetch(MYSQLI_ASSOC)) {
if ($outp != "")
array_push($outp,$rs["nom"]);
}
$outp =json_encode($outp);
$conn = null;
echo($outp);
?>
答案 1 :(得分:0)
好的,我明白了。 Arun Shinde的回答是对的,但问题来自:
while($rs = $result->fetch(MYSQLI_ASSOC)) {
我正在使用PDO,所以在这里使用MYSQLI显然不会起作用。 所以这里有完整的代码。 home.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr ng-repeat="x in names"> <td>{{ x }}</td> </tr>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("server.php")
.then(function (response) {
$scope.names = response.data;
}).then(function(response){
console.log(response)
})
});
</script>
</body>
server.php:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new PDO('mysql:host=localhost;dbname=mygaloo;charset=utf8', 'root', '');
$result = $conn->query("SELECT * FROM associations");
$outp = [];
while($rs = $result->fetch()) {
if ($outp != "")
array_push($outp,$rs["nom"]);
}
$outp =json_encode($outp);
$conn = null;
echo($outp);
?>
非常感谢大家的耐心!