[AngularJS]Chapter 5 与服务器交互

本文详细介绍了AngularJS中HTTP请求的使用方法,包括GET、POST请求的实现方式,如何定制HTTP请求,设置请求头,利用缓存提升应用性能等。

第八章有关于缓存的东西。

【通过$http交互】

传统的AJAX请求如下

 1 var xmlhttp = new XMLHttpRequest();
 2 xmlhttp.onreadystatechange = function() {
 3 if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {
 4 var response = xmlhttp.responseText;
 5 } else if (xmlhttp.status == 400) { // or really anything in the 4 series
 6 // Handle error gracefully
 7 }
 8 };
 9 // Setup connection
10 xmlhttp.open(“GET”, “http://myserver/api”, true);
11 // Make the request
12 xmlhttp.send();
View Code

AngularJS Get请求如下,跟jQuery很相似

1 $http.get('api/user', {params: {id: '5'}
2 }).success(function(data, status, headers, config) {
3 // Do something successful.
4 }).error(function(data, status, headers, config) {
5 // Handle the error
6 });
View Code

AngularJS Post请求如下

 1 var postData = {text: 'long blob of text'};
 2 // The next line gets appended to the URL as params
 3 // so it would become a post request to /api/user?id=5
 4 var config = {params: {id: '5'}};
 5 $http.post('api/user', postData, config
 6 ).success(function(data, status, headers, config) {
 7 // Do something successful
 8 }).error(function(data, status, headers, config) {
 9 // Handle the error
10 });
View Code

【定制你的http请求】

安哥拉提供了一个开箱即用的机制,一帮情况下足够了。但是如果你想:

  添加一些授权消息头

  改变请求的缓存状态

  定制请求和响应

代码如下

 1 $http({
 2 method: string,
 3 url: string,
 4 params: object,
 5 data: string or object,
 6 headers: object,
 7 transformRequest: function transform(data, headersGetter) or
 8 an array of functions,
 9 transformResponse: function transform(data, headersGetter) or
10 an array of functions,
11 cache: boolean or Cache object,
12 timeout: number,
13 withCredentials: boolean
14 });
View Code

【设置http请求头】

AngularJS有默认的头:如下

1. Accept: application/json, text/plain, /
2. X-Requested-With: XMLHttpRequest

如果你想加新的。有两种方式:

第一种:修改默认的请求头

1 angular.module('MyApp',[]).
2 config(function($httpProvider) {
3 // Remove the default AngularJS X-Request-With header
4 delete $httpProvider.default.headers.common['X-Requested-With'];
5 // Set DO NOT TRACK for all Get requests
6 $httpProvider.default.headers.get['DNT'] = '1';
7 });
View Code

第二种:修改某次请求头

1 $http.get('api/user', {
2 // Set the Authorization header. In an actual app, you would get the auth
3 // token from a service
4 headers: {'Authorization': 'Basic Qzsda231231'},
5 params: {id: 5}
6 }).success(function() { // Handle success });
View Code

【缓存响应】

可以这样开启缓存

1 $http.get('http://server/myapi', {
2 cache: true
3 }).success(function() { // Handle success })
View Code

【请求与响应间的变化】

 

转载于:https://www.cnblogs.com/tonghounb/p/3476007.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值