ANGULARJS Request resources from the Web server is done through Ajax , all the operations encapsulated in the $http service, $http service is a function that can only receive one parameter, this parameter is an object, used to complete the HTTP request configuration, The function returns an object with success and error two methods.
Use the following:
$http({method:
‘post‘
,url:
‘loginAction.do‘
}).success(
function
(data,status,headers,config){
//正常响应回调
}).error(
function
(data,status,headers,config){
//错误响应回调
});
The status code between 200-299, the response is considered to be successful, the success method will be called, the first parameter data is the server-side of the return, status is the response state code. The following two parameters are not commonly used and are not introduced here. Interested friends please refer to the ANGULARJS API documentation.
In addition, the $http service provides a number of quick ways to simplify complex configurations and simply provide URLs. For example, for a POST request we can write the following:
$http.post(
"loginAction.do"
)
.success(
function
(data,status,headers,config){
//正常响应回调
}).error(
function
(data,status,headers,config){
//错误响应回调
});
Let's look at a case:
<!DOCTYPE html>
"serverMod"
>
"en"
>
<meta charset=
"UTF-8"
>
<script type=
"text/javascript"
src=
"angular-1.3.0.14/angular.js"
></script>
<title>tutorial09</title>
<body ng-controller=
"ServerController"
ng-init=
"init()"
>
<p>name:{{name}}</p>
<p>age:{{age}}</p>
<button ng-click=
"getInfo()"
>请求</button>
</body>
<script>
var
serverMod = angular.module(
"serverMod"
,[]);
serverMod.controller(
"ServerController"
,
function
($scope,$log,$http){
$scope.init =
function
()
{
$log.info(
"init functionn"
);
}
$scope.getInfo =
function
()
{
$http.get(
"json/person.json"
).success(
function
(data,status){
alert(status);
$scope.name = data.name;
$scope.age = data.age;
});
}
});
</script>
Click the "Request" button, we through the $http service to get the server to request data, the server response data format is usually a JSON, here we use a text file instead, Person.json content as follows:{
"name"
:
"Rongbo_J"
,
"age"
:
"23"
}
Example of interaction with the server (Ajax) Angularjs Getting Started tutorial