AngularJS XMLHttpRequest


$http is an AngularJS service for reading data from remote servers.


Reading a JSON File

The following static JSON file is stored on a web server:

http://www.w3schools.com/website/Customers_JSON.php

[
{
"Name" : "Alfreds Futterkiste",
"City" : "Berlin",
"Country" : "Germany"
},
{
"Name" : "Berglunds snabbköp",
"City" : "Luleå",
"Country" : "Sweden"
},
{
"Name" : "Centro comercial Moctezuma",
"City" : "México D.F.",
"Country" : "Mexico"
},
{
"Name" : "Ernst Handel",
"City" : "Graz",
"Country" : "Austria"
},
{
"Name" : "FISSA Fabrica Inter. Salchichas S.A.",
"City" : "Madrid",
"Country" : "Spain"
},
{
"Name" : "Galería del gastrónomo",
"City" : "Barcelona",
"Country" : "Spain"
},
{
"Name" : "Island Trading",
"City" : "Cowes",
"Country" : "UK"
},
{
"Name" : "Königlich Essen",
"City" : "Brandenburg",
"Country" : "Germany"
},
{
"Name" : "Laughing Bacchus Wine Cellars",
"City" : "Vancouver",
"Country" : "Canada"
},
{
"Name" : "Magazzini Alimentari Riuniti",
"City" : "Bergamo",
"Country" : "Italy"
},
{
"Name" : "North/South",
"City" : "London",
"Country" : "UK"
},
{
"Name" : "Paris spécialités",
"City" : "Paris",
"Country" : "France"
},
{
"Name" : "Rattlesnake Canyon Grocery",
"City" : "Albuquerque",
"Country" : "USA"
},
{
"Name" : "Simons bistro",
"City" : "København",
"Country" : "Denmark"
},
{
"Name" : "The Big Cheese",
"City" : "Portland",
"Country" : "USA"
},
{
"Name" : "Vaffeljernet",
"City" : "Århus",
"Country" : "Denmark"
},
{
"Name" : "Wolski Zajazd",
"City" : "Warszawa",
"Country" : "Poland"
}
]


AngularJS $http

AngularJS $http is a core service for reading data from web servers.

$http.get(url) is the function to use for reading server data.

AngularJS Example

<div ng-app="" ng-controller="customersController">

<ul>
  <li ng-repeat="x in names">
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>

</div>

<script>
function customersController($scope,$http) {
    $http.get("http://www.w3schools.com/website/Customers_JSON.php")
    .success(function(response) {$scope.names = response;});
}
</script>

Try it Yourself »

Application explained:

The AngularJS application is defined by ng-app. The application runs inside a <div>.

The ng-controller directive names the controller object.

The customersController function is a standard JavaScript object constructor.

AngularJS will invoke customersController with a $scope and $http object.

$scope is the application object (the owner of application variables and functions).

 $http is an XMLHttpRequest object for requesting external data.

$http.get() reads static JSON data from http://www.w3schools.com/website/Customers_JSON.php.

If success, the controller creates a property (names) in the scope, with JSON data from the server.

Note The code above can also be used to fetch data from a database.


Color Picker

colorpicker