Reputation: 2485
I have a PHP server page returning data in JSON format like this:
<?php
$data = array(
(object)array(
'title' => 'myfirstvalue',
'value' => 'myfirsttext',
),
(object)array(
'title' => 'mysecondvalue',
'value' => 'mysecondtext',
),
);
$json = json_encode($data);
echo $json;
?>
Now I'd need to display the JSON title attribute using AngularJS. Taken from a tutorial I've adapted the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="MyController" >
<button ng-click="myData.doClick(item, $event)">Send AJAX Request</button>
<br/>
Data from server: {{myData.fromServer}}
</div>
<script>
angular.module("myapp", [])
.controller("MyController", function($scope, $http) {
$scope.myData = {};
$scope.myData.doClick = function(item, event) {
var responsePromise = $http.get("http://localhost/myfunction.php");
responsePromise.success(function(data, status, headers, config) {
$scope.myData.fromServer = data.title;
});
responsePromise.error(function(data, status, headers, config) {
alert("AJAX failed!");
});
}
} );
</script>
</body>
</html>
However nothing is displayed when I click on the button. Any idea where is the problem with this code ? Thanks!
Upvotes: 0
Views: 334
Reputation: 5668
Line
$scope.myData.fromServer = data.title;
isn't good. In general 'yes' but not in these piece of code. Why? You PHP code return:
array(
[0] => array(
'title' => ...,
'value' => ....
),
[1] => array(
'title' => ...,
'value' => ....
)
);
You don't have key 'title' there. You should use data[0].title to display results (key '0').
I preferring to use in these case UnderscoreJS (underscorejs.org). Method _.pluck(list, propertyName) seems for me to be good. Read more here - http://underscorejs.org/#pluck
Upvotes: 1