AngularJS XMLHttpRequest
$httpIt is a core service in AngularJS, used to read data from a remote server.
Usage Format:
// 简单的 GET 请求,可以改为 POST
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// 请求成功执行代码
}, function errorCallback(response) {
// 请求失败执行代码
});
Shorthand Methods
POST and GET Shorthand Method Format:
$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
In addition, there are the following shorthand methods:
- $http.get
- $http.head
- $http.post
- $http.put
- $http.delete
- $http.jsonp
- $http.patch
For more details, see:https://docs.angularjs.org/api/ng/service/$http
Read JSON File
The following is a JSON file stored on the web server:
https://www.example.com/try/angularjs/data/sites.php
AngularJS $http
AngularJS $http is a service used to read data on a web server.
$http.get(url) is a function used to read server data.
Deprecation Notice (v1.5)
In v1.5,
$httpofsuccessanderrorthe method has been deprecated. Usethenmethod instead.
Generic Method Example
AngularJS 1.5 and above - Example
Try it Yourself »
Shorthand Method Example
AngularJS 1.5 and above - Example
Try it Yourself »
AngularJS 1.5 and below - Example
Try it Yourself »
Application Analysis:
Note: The GET request in the above code targets this site's server. You cannot directly copy it and run it locally, as there will be cross-domain issues. The solution is to copy the data from Customers_JSON.php to your own server. See:Best Solutions for PHP Ajax Cross-Domain Issues。
The AngularJS application is defined viang-appthe `ng-app` directive. The application executes in the <div>.
ng-controllerThe directive sets the`controller` objectname.
The functioncustomersControlleris a standard JavaScriptobject constructor.。
The controller object has a property:$scope.names。
$http.get()Reads staticJSON data from the web server.。
The server data file is: https://www.example.com/try/angularjs/data/sites.php。
When loading JSON data from the server,$scope.namesit becomes an array.
![]() |
The above code can also be used to read database data. |
|---|
