加载中...

HTTP请求


11.1. HTTP请求

基本的操作由 $http 服务提供。它的使用很简单,提供一些描述请求的参数,请求就出去了,然后返回一个扩充了 success 方法和 error 方法的 promise 对象(下节介绍),你可以在这个对象中添加需要的回调函数。

  1. var TestCtrl = function($scope, $http){
  2. var p = $http({
  3. method: 'GET',
  4. url: '/json'
  5. });
  6. p.success(function(response, status, headers, config){
  7. $scope.name = response.name;
  8. });
  9. }

$http 接受的配置项有:

  • method 方法
  • url 路径
  • params GET请求的参数
  • data post请求的参数
  • headers 头
  • transformRequest 请求预处理函数
  • transformResponse 响应预处理函数
  • cache 缓存
  • timeout 超时毫秒,超时的请求会被取消
  • withCredentials 跨域安全策略的一个东西

其中的 transformRequesttransformResponseheaders 已经有定义的,如果自定义则会覆盖默认定义:

  1. 1 var $config = this.defaults = {
  2. 2 // transform incoming response data
  3. 3 transformResponse: [function(data) {
  4. 4 if (isString(data)) {
  5. 5 // strip json vulnerability protection prefix
  6. 6 data = data.replace(PROTECTION_PREFIX, '');
  7. 7 if (JSON_START.test(data) && JSON_END.test(data))
  8. 8 data = fromJson(data, true);
  9. 9 }
  10. 10 return data;
  11. 11 }],
  12. 1213 // transform outgoing request data
  13. 14 transformRequest: [function(d) {
  14. 15 return isObject(d) && !isFile(d) ? toJson(d) : d;
  15. 16 }],
  16. 1718 // default headers
  17. 19 headers: {
  18. 20 common: {
  19. 21 'Accept': 'application/json, text/plain, /',
  20. 22 'X-Requested-With': 'XMLHttpRequest'
  21. 23 },
  22. 24 post: {'Content-Type': 'application/json;charset=utf-8'},
  23. 25 put: {'Content-Type': 'application/json;charset=utf-8'}
  24. 26 }
  25. 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 会为你替换成真正的函数名:

  1. var p = $http({
  2. method: 'JSONP',
  3. url: '/json',
  4. params: {callback: 'JSON_CALLBACK'}
  5. });
  6. p.success(function(response, status, headers, config){
  7. console.log(response);
  8. $scope.name = response.name;
  9. });

$http 有两个属性:

  • defaults 请求的全局配置
  • pendingRequests 当前的请求队列状态

    $http.defaults.transformRequest = function(data){console.log('here'); return data;}
    console.log($http.pendingRequests);


还没有评论.