$http 是 AngularJS 中的一个核心服务,用于读取远程服务器的数据。
它是一个特殊的内置服务,主要用于进行异步数据请求的功能实现;
使用格式:
$http({
method:"GET",
url:"",
params:{status:"",...}
/*如果是get请求,请使用params来传递参数
如果是Post请求,请使用data来尝试传递参数*/
}).then(
function success(resp) {
// 成功处理函数
},
function error(resp) {
// 请求失败处理函数
}
)
AngularJS $http 是一个用于读取web服务器上数据的服务。
$http.get(url) 是用于读取服务器数据的函数。
登录页面应用实例:
<html ng-app="myApp">
<head>
<title>登录页面</title>
<script src="angular.min.js"></script>
</head>
<body>
<div class="form" ng-controller="login">
账号:<input type="text" ng-model="username"><br />
密码:<input type="text" ng-model="password"><br />
<button ng-click="loginFn()">登录</button>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("login", ["$scope", "$http",
function($scope, $http) {
$scope.loginFn = function() {
// 实现登录
$http({
method:"GET",
url:"http://datainfo.duapp.com/shopdata/userinfo.php",
params:{status:"login",userID:$scope.username, password:$scope.password}
/*
如果是get请求,请使用params来传递参数
如果是Post请求,请使用data来尝试传递参数
*/
}).then(
function success(resp) {
console.log("请求成功", resp);
if(resp.data instanceof Object) {//判断resp.data是否为对象
console.log("登录成功,跳转到首页");
} else {
console.log("登录失败");
}
},
function error(resp){
console.log("请求失败");
}
);
}
}]);
</script>
</body>
</html>
参数:
method:请求方法。
url:请求地址。
params:字符串或者对象,作为GET请求的参数。
data:字符串或者对象,作为请求信息数据的数据(请求内容)。
status :数值,响应的http状态码。