服务端交互介绍
7.1.2 使用$http快捷方式与服务端交互
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>7.1.2 $http服务模块与服务端交互</title>
</head>
<body>
<div ng-controller="contro" ng-app="myapp">
<div>
<div>post返回结果:{{result}}</div>
<button ng-click="onclick()">发送</button>
</div>
</div>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script>
angular.module('myapp',[])
.config(function($httpProvider){ //调用config方法,注入$httpProvider服务
$httpProvider.defaults.transformRequest = //重置transformRequest函数
function(obj){
var arrStr = [];
for(var p in obj){
arrStr.push(encodeURIComponent(p)+"="+encodeURIComponent(obj[p]));
}
return arrStr.join("&");
}
$httpProvider.defaults.headers.post = {
'Content-Type': //post请求需要重置Content-Type值
'application/x-www-form-urlencoded'
}
})
.controller('contro',function($scope,$http){
var postData = {name:"张桂芳"};
$scope.onclick = function(){
$http.post('data/post.php',postData)
.success(function(data,status,headers,config)){
$scope.result = data;
}
}
})
</script>
</body>
</html>
7.1.3 $http配置对象方式与服务器端交互
$http({
method: //POST、GET、JSONP、DELETE、PUT、HEAD
url:
data: //作为一个对象,发送给服务端,常用于post和put
params: //字符串或对象,序列化后追加到URL后面,传递给服务器
transformRequest: //序列化转换
transformResponse: //反序列化转换
cache: //true 缓存
timeout: //延迟发送,ms
})
eg:
<%@page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>7.1.3 $http配置对象方式与服务器端交互</title>
<style>
*{
margin: 0;
padding:0;
}
li{
list-style: none;
}
.file{
width: 300px;
padding: 5px;
background: #eee;
font-family: "微软雅黑";
font-size: 12px;
border-radius: 5px;
margin-top: 10px;
}
.file li{
height: 30px;
line-height: 30px;
}
.file span{
display: block;
float: left;
width: 150px;
}
</style>
</head>
<body>
<div ng-controller="contro" ng-app="myapp">
<input type="text" ng-model = "num">
<button ng-click="onclick()">获取报表列</button>
<div>
<ul class="file">
<li ng-repeat="file in result">
<span>列名:{{file.name}}</span>
<span>宽度:{{file.width}}</span>
</li>
</ul>
</div>
</div>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script>
angular.module('myapp',[])
.controller('contro',function($scope,$http){
$scope.num = 199199;
$scope.onclick = function(){
$http({
method:'POST',
url:'/sce-dw-rpt/loadReportTable',
data:$scope.num
})
.success(function(data,status,headers,config){
$scope.result = data.tableList;
})
}
})
</script>
</body>
</html>
根据表id查询表列信息 返回数据 data
注:
因为$http返回的是一个promise对象,一下两种方式是等价的
$http({
})
.success(fn1)
.error(fn2)
==============
$http({
})
.then(fn1,fn2) //then方法 可以接受服务端完整响应对象