The following code can be used to get the data from the web server.
index.html
[html]
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.3.14" data-semver="1.3.14" src="https://code.angularjs.org/1.3.14/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="Controller.js"></script>
</head>
<body ng-app="spApp">
<h1>AJAX Http</h1>
<div ng-controller="SPController">
<p>Today's welcome message is:</p>
<h1>{{message}}</h1>
</div>
<p>The $http service requests a page on the server, and the response is set as the value of the "message" variable.</p>
</body>
</html>
[/html]
Controller.js
[javascript]
var MyApp = angular.module('spApp', []);
MyApp.controller("SPController", function($scope, $http) {
var url="message.php";
$http.get(url)
.success(function(response) {
$scope.message = response;
});
});
[/javascript]
message.php
[php]
SPLessons AngularJS Tutorial
[/php]
Output:
$http
service having different Ajax functions returns a promise object. success()
and error()
are the two functions of promise object that takes call back functions as parameters.
From the above example,
response
is a parameter to
success()
and
error()
functions depending on the Ajax request. If the Ajax request is successful,
response
parameter is passed to
success()
function or
error()
function in the case of failure.
success():
success()
function is executed when the response is available.
error():
error()
function is executed when the server returns the response with an error status.