基本上我想做的是从我的数据库中进行 ng-repeat 记录,但是,我收到以下错误“SyntaxError:JSON 中位置 0 处出现意外的标记 F”。
这是我的代码:
HTML
<tr ng-repeat="x in data">
<td>{{x.songName}}</td>
<td>{{x.albumName}}</td>
</tr>
JS
$scope.loadTracks = function(){
$http.get('includes/functions/gettrack.php').success(function(data){
$scope.data = data;
})
}
PHP
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
$data = array();
$sql = "SELECT * FROM tracks";
// Create a prepared statement
$stmt = mysqli_stmt_init($connection);
// Prepare the prepared statement
if (!mysqli_stmt_prepare($stmt, $sql)) {
// Error exists
die('Fatal error: service unavailable at this time');
} else {
// Run parameters inside the database
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($result) > 0) {
// Check for results and assign results to array
while ($row = $result->fetch_assoc()){
$data[] = $row;
}
echo json_encode($data);
}
}
?>
最佳答案
我怀疑您的代码正在执行die(' fatal error :服务此时不可用');
。该字符串的字符 0 是 F
,与您的错误匹配。
JS 将尝试解码 fatal error :此时服务不可用
,这不是有效的 JSON。
die()未设置 http 代码,因此 AJAX 请求将被视为成功。尝试使用 http_response_code() 设置代码:
if (!mysqli_stmt_prepare($stmt, $sql)) {
// Error exists
http_response_code(500);
die('Fatal error: service unavailable at this time');
} else {
您还应该调整 AJAX 调用来处理错误:
$http.get('includes/functions/gettrack.php').success(function(data){
$scope.data = data;
}).fail(function(){
console.error('AJAX call failed');
});
或者,您可以更改 die() 内返回的字符串。 ,但我建议这并不是解决这个问题的好方法。
die('"Fatal error: service unavailable at this time"');
关于javascript - 使用 Angularjs 显示数据库中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47200180/