$http的使用方式
$http:是对原生的XMLHttpRequest对象的封装
var app = angular.module('myApp', []);
// 创建Controller,测试$http如何与服务器交互
app.controller("MyController", function ($scope, $http) {
// 1 基本使用方式,只接受一个参数,config对象
$http({
// 设置目标url,通常不会是一个json文件,而是后台的php或者jsp文件,通过其查询数据
url: "data/users.json",
method: "get"
}).success(function (data,status,headers,config) {
// data 是返回数据
$scope.users=data.users;
// status 是响应状态代码
// headers 是响应头处理函数
console.log(headers("cache-control"));
// config是完整的配置对象
}).error(function (data,status,headers,config) {
// 发生了错误。只要不在200-299之间,就认为发生了错误
console.log(data);
});
// 2 then方法的使用
$http({
// 设置目标url,通常不会是一个json文件,而是后台的php或者jsp文件,通过其查询数据
url: "data/users.json",
method: "get"
}).then(
function (res) {
// res是响应对象
console.log(res);
$scope.users=res.data.users;
}, function (res) {
// 发生了错误。只要不在200-299之间,就认为发生了错误
console.log(res);
});
// 3 简写形式 get()/post()/delete()/put()/jsonp()/head()
$http.get("data/users.json").success(function (data) { //get方法返回的还是promise对象
$scope.users=data.users;
});
})
<!-- $http的使用-->
<ul>
<li ng-repeat="user in users">
姓名:{{user.name}}
年龄:{{user.age}}
</li>
</ul>