gpt4 book ai didi

javascript - 在 angularjs 中处理 json 响应(来自 PHP 和 mysql)

转载 作者:行者123 更新时间:2023-11-29 21:39:09 24 4
gpt4 key购买 nike

在处理来自 php 的 Json 响应时遇到麻烦。我正在使用 AngularJs 显示收到的 Json 数据。我是 Angular 新手,尝试了一个简单的初学者练习。请帮忙。提前致谢。

index.html

<!DOCTYPE HTML>

<html ng-app="app">
<head>
<title>PHP MySQL API Consumed with AngularJS</title>
</head>

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

<table border="1">
<thead><tr><th>ID</th><th>Name</th><th>City</th></tr></thead>
<tbody>
<tr ng-repeat="user in users"><td>{{user.user_id}}</td><td> {{user.first_name }}</td><td>{{user.user_city}}</td></tr>
</tbody>
</tfoot></tfoot>
</table>
</div>
<script>

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

app.controller('GetUsers', function ($scope,$http){
$http.get('http://localhost/angmysql/api.php').success(function(data) {
$scope.users = data;
});
}
});

</script>

<script src="angular.js"></script>

<body>
</html>

api.php

<?php

$db_name = 'dbtuts';
$hostname = 'localhost';
$username = 'root';
$password = '';

$dbc = mysqli_connect('localhost','root','','dbtuts') or die('Error connecting to database');

$sql = mysqli_query($dbc,"SELECT * FROM users");

$emparray = array();

while($row =mysqli_fetch_assoc($sql))
{
$emparray[] = $row;
}

echo json_encode($emparray);

mysqli_close($dbc);
?>

最佳答案

$http 传入回调的参数是一个对象,其中响应正文存储在 .data 字段中。

试试这个:

$http.get('http://localhost/angmysql/api.php').success(function(response) {
$scope.users = response.data;
});

来自AngularDocs

The response object has these properties:

data – {string|Object} – The response body transformed with the transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.

关于javascript - 在 angularjs 中处理 json 响应(来自 PHP 和 mysql),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34677576/

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