angular ajax 浅析
- ajax
angular 提供了基本的 AJAX 封装,你直接面对 promise 对象,使用起来还是很方便的。
1.1 HTTP请求
基本的操作由 $http 服务提供。它的使用很简单,提供一些描述请求的参数,请求就出去了,然后返回一个扩充了 success 方法和 error 方法的 promise 对象(下节介绍),你可以在这个对象中添加需要的回调函数。
var TestCtrl = function($scope, $http){ var p = $http({ method: 'GET', url: '/json' }); p.success(function(response, status, headers, config){ $scope.name = response.name; }); }
$http 接受的配置项有:
- method 方法
- url 路径
- params GET请求的参数
- data post请求的参数
- headers 头
- transformRequest 请求预处理函数
- transformResponse 响应预处理函数
- cache 缓存
- timeout 超时毫秒,超时的请求会被取消
- withCredentials 跨域安全策略的一个东西
其中的 transformRequest 和 transformResponse 及 headers 已经有定义的,如果自定义则会覆盖默认定义:
var $config = this.defaults = { 2 // transform incoming response data 3 transformResponse: [function(data) { 4 if (isString(data)) { 5 // strip json vulnerability protection prefix 6 data = data.replace(PROTECTION_PREFIX, ''); 7 if (JSON_START.test(data) && JSON_END.test(data)) 8 data = fromJson(data, true); 9 } 10 return data; 11 }], 12 13 // transform outgoing request data 14 transformRequest: [function(d) { 15 return isObject(d) && !isFile(d) ? toJson(d) : d; 16 }], 17 18 // default headers 19 headers: { 20 common: { 21 'Accept': 'application/json, text/plain, */*', 22 'X-Requested-With': 'XMLHttpRequest' 23 }, 24 post: {'Content-Type': 'application/json;charset=utf-8'}, 25 put: {'Content-Type': 'application/json;charset=utf-8'} 26 } 27 };
注意它默认的 POST 方法出去的 Content-Type
对于几个标准的 HTTP 方法,有对应的 shortcut :
- $http.delete(url, config)
- $http.get(url, config)
- $http.head(url, config)
- $http.jsonp(url, config)
- $http.post(url, data, config)
- $http.put(url, data, config)
注意其中的 JSONP 方法,在实现上会在页面中添加一个 script
标签,然后放出一个 GET 请求。你自己定义的,匿名回调函数,会被 ng 自已给一个全局变量。在定义请求,作为 GET 参数,你可以使用 JSON_CALLBACK
这个字符串来暂时代替回调函数名,之后 ng 会为你替换成真正的函数名:
$http({ method:'JSONP', url:'/test.json', params:{} }).success(function(response, header, headers, config){ });
1.2 ajax 请求跨域
在实际开发中,通常会遇到ajax跨域问题。解决办法有两个:nginx反向代理、cors。推荐用nginx反向代理。