我有一个包含数组的json文件:
{
"people": [
{"number":"1", "name":"Gary", "surname":"Peterson", "age":"25"},
{"number":"2", "name":"Andy", "surname":"Smith", "age":"26"},
{"number":"3", "name":"Michael", "surname":"Johnson", "age":"28"}
]
}
我想只将第一个对象(人员记录)返回给我的应用程序。 当我在AngularJS中调用http服务并传递参数时,如下所示:
angular.module('mod', [])
.controller('ctrl', function($scope, $http){
$scope.serviceMethod = function(){
$http.get("url to database.json", {params: {number: 1}})
.then(function Succes(response) {$scope.person = response.data.people;});};
});
它返回所有三个对象。我在控制台的控制台中看到没有错误(状态200)并且参数IS已通过(它构建了这个URL:http://urltowebsite.com/database.json?number=1)。
我在这里缺少什么?
答案 0 :(得分:1)
在你的问题中你声明你有一个包含记录的JSON文件(我认为它在服务器端)并且你希望这个记录被这个JSON文件过滤掉然后我的回答是JSON文件没有能力过滤其记录。
为此您需要服务器端应用程序来读取此请求
http://urltowebsite.com/database.json?number=1
此服务器端应用程序将访问该JSON文件,过滤记录并仅将特定记录返回给AngularJS。
然后你不需要任何逻辑来过滤AngularJS方面的记录。
答案 1 :(得分:1)
根据您的要求,您应该使用基于number
属性过滤数据库记录的服务器端语言,并创建结果的json object
。
我使用PHP来理解功能:
Angular Code:
angular.module('mod', [])
.controller('ctrl', function($scope, $http){
$scope.serviceMethod = function(){
$http.get("getRecord.php", {number: 1})
.then(function Succes(response) {$scope.person = response;});};
});
getRecord.php:
<?php
$data = json_decode(file_get_contents("php://input"));
$number = $data->number;
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('db_name', $con);
$query = 'select * from table_name WHERE number = 1';
$query_result = mysql_query($query);
$res = mysql_fetch_assoc($query_result);
do
{
$resultdata[] = $res;
}while($res = mysql_fetch_assoc($query_result));
echo json_encode($resultdata);
mysql_close($con);
?>
或者,如果您只想要JSON中的第一条记录,那么您可以尝试使用此记录。
$scope.person = response.data.people[0];
我希望它能奏效。感谢。
答案 2 :(得分:0)
如果您只想要第一人称记录,您可以尝试这样的事情:
$scope.person = response.data.people[0];
如果您希望在服务器上处理此问题,则需要使用后端API来处理它并仅返回people数组的第一个对象。
答案 3 :(得分:0)
您无法使用参数访问json文件。您已正确从json中提取数据,因此现在您可以在视图网站上选择要显示的内容。