首先,在此先感谢您的帮助。我已经努力了几天,试图弄清楚如何将一个角度图表对象挂接到mysql数据库中。我目前有使用静态数据的图表。我的项目中有一个通用的php文件,看起来像这样:
// Create the connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
//the sql to run
$sql = "SELECT * FROM Test2";
//run it
$result = $conn->query($sql);
//check for results
if ($result->num_rows > 0) {
//create an array
$dataarray[] = array();
//loop em
while($row =mysqli_fetch_assoc($result)) {
$dataarray[] = $row;
}
//make em json
echo json_encode($dataarray);
}
//} else {
// echo "0 results";
//}
//close out our connection
$conn->close();
?>
这很好。该表返回带有标题名称和值的几行。目前仅测试数据。
在我的html / javascript中,我具有以下内容:
<script>
angular.module("ChartApp", ["chart.js"]).controller("PieCtrl", function ($scope, $http) {
$http.get('./GetTestData.php').
success(function(data) {
$scope.records = data;
});
$scope.labels = ["Download Sales", "In-Store Sales", "Mail-Order Sales"];
$scope.data = [300, 500, 100];
});
</script>
我不太确定从这儿去哪里。任何帮助,将不胜感激。
最佳答案
花了很长时间,但我终于想通了。我必须采用JSON对象并将值转换为单独的数组。以下是相关代码:
angular.module("ChartApp", ["chart.js"]).controller("PieCtrl", function ($scope, $http) {
$http.get('./GetTestData.php').
success(function(data) {
var names = [];
for(var i = 0; i < data.length; i++) {
var obj = data[i];
if(obj.Name != undefined) {
names.push(obj.Name);
}
}
var values = [];
for(var i = 0; i < data.length; i++) {
var obj = data[i];
if(obj.Name != undefined) {
values.push(obj.Value);
}
}
//$scope.records = data;
$scope.labels = names;
$scope.data = values;
});
});
</script>