$http使用验证,澳门娱乐6165AngularJS 提供了一个

作者:澳门娱乐

AngularJS 中 异步请求$http 对象的使用

??

AngularJS 提供了一个类似jquery的$.ajax的对象,用于异步请求。
在AngularJS中对异步操作是推崇至极的,所以$http的操作都是异步的不像jquery.ajax里还提供了async参数。

 

对于官网的$http对象的总结和使用。**

 

用法:

$http(config);

参数:

config (常用的参数标红,翻译了一下)

config object

Object describing the request to be made and how it should be processed. The object has following properties:

  • method{string} – HTTP method (e.g. 'GET', 'POST', etc) ------------------ http交互方法:GET/POST 两种
  • url{string} – Absolute or relative URL of the resource that is being requested. ------------------ URL传输地址
  • params{Object.} – Map of strings or objects which will be serialized with theparamSerializer and appended as GET parameters. ------------------ Map 类型的参数,传输给后台
  • data{string|Object} – Data to be sent as the request message data. ------------------ 要求传入的参数
  • headers{Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. Functions accept a config object as an argument.
  • xsrfHeaderName{string} – Name of HTTP header to populate with the XSRF token.
  • xsrfCookieName{string} – Name of cookie containing the XSRF token.
  • transformRequest{function(data, headersGetter)|Array.} – transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version. See Overriding the Default Transformations
  • transformResponse{function(data, headersGetter, status)|Array.} – transform function or an array of such functions. The transform function takes the http response body, headers and status and returns its transformed (typically deserialized) version. See Overriding the Default TransformationjqLiks
  • paramSerializer - {string|function(Object):string} - A function used to prepare the string representation of request parameters (specified as an object). If specified as string, it is interpreted as function registered with the $injector, which means you can create your own serializer by registering it as a service. The default serializer is the $httpParamSerializer; alternatively, you can use the$httpParamSerializerJQLike
  • cache{boolean|Cache} – If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching. ------------------ 缓存,设为true的时候,默认的$ HTTP缓存将用于缓存GET请求,否则,创建Factory缓存实例.
  • timeout{number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.
  • withCredentials - {boolean} - whether to set the withCredentials flag on the XHR object. See requests with credentials for more information.
  • responseType - {string} - see XMLHttpRequest.responseType.

 

返回: 一个httpPromise对象(一般只用data和status)

HttpPromise

Returns a promise object with the standard then method and two http specific methods: success and error. Thethen method takes two arguments a success and an error callback which will be called with a response object. Thesuccess and error methods take a single argument - a function that will be called when the request succeeds or fails respectively. The arguments passed into these functions are destructured representation of the response object passed into the then method. The response object has these properties:

  • data{string|Object} – The response body transformed with the transform functions. ------------------ 返回数据
  • status{number} – HTTP status code of the response. ------------------ 返回状态。等于200时为成功,否则失败。
  • headers{function([headerName])} – Header getter function.
  • config{Object} – The configuration object that was used to generate the request. ------------------ 用于生成请求的配置对象,原来传入的参数等。
  • statusText{string} – HTTP status text of the response. ------------------ 返回的状态文本

方法:

get(url, [config]); 快捷的方法来执行GET请求。

post(url, data, [config]); 快捷的方法来执行POST请求。

put(url, data, [config]);

patch(url, data, [config]);

 

jsonp(url, [config]);

head(url, [config]);

delete(url, [config]);

 

 

我自己的使用例子(使用promise解决回调地狱问题)

 

          var deferred = $q.defer();
          $http({
            cache: false,
            method: 'GET',
            url: Constants.baseURL + '/loginj',
            params: params,
            headers: {'X-Auth-Token': $window.token}
          }).then(function(res) {
            if (200 === res.status && res.data.LoginResponse.success) {
              if (!Array.isArray(res.data.LoginResponse.settings.account)) {
                res.data.LoginResponse.settings.account = [res.data.LoginResponse.settings.account];
              }

              CurrentUser.id = res.data.LoginResponse.settings.id;

              deferred.resolve(res.data.LoginResponse.settings);
            } else {
              deferred.reject(failed to fetch login data);
            }
          }, function(error) {
              deferred.reject(error.status+ +error.statusText);
          });
          return deferred.promise;

 

 

 

 

中 异步请求$http 对象的使用 ?? AngularJS 提供了一个 类似jquery的$.ajax 的对象,用于异步请求。 在AngularJS中对异步操作是推崇至极的,...

在AngularJS中主要使用$http服务与远程http服务器交互,其作用类似于jquery中的$.ajax服务:

$http是AngularJS的一个核心服务,利用浏览器的xmlhttprequest或者via JSONP对象与远程HTTP服务器进行交互; 与$.ajax相同,支持多种method请求:get、post、put、delete等; controller中可通过与$scope同样的方式获取$http对象,形如:function controller{};

$http使用说明:

$http服务使用如下面代码所示:

// 1.5以下版本$http.success(function(data, status, headers, config){//请求成功执行代码}).error(function(data, status, headers, config){//请求失败执行代码})// 1.5以上版本$http.then(function successCallback{//请求成功执行代码},function errorCallback{//请求失败执行代码});

具体参数、方法说明:

config是请求的配置参数总集,格式为json; 包含的配置项包括: method:字符串类型,请求方式如"GET","POST","DELETE"等; url:字符串类型,请求的url地址; params:json类型,请求参数,将在url上被拼接成?key=value的形式; data:json类型,请求数据,将放在请求内发送至服务器; cache:bool类型,true表示http GET请求时采用默认的$http cache,否则使用$cacheFactory的实例; timeout:整数类型,超时时间;

回调函数:

success是请求成功后的回调函数; error是请求失败后的回调函数; data是响应体; status是相应的状态值; headers是获取getter的函数; config是请求中的config json对象;

method属性可以作为config配置参数中的一个属性,也可以直接作为方法调用,如:

$http.post

$http使用范例:

var searchOplog = function  { $http({ url: 'data/oplog.json', method: 'GET' }).then(function successCallback { console.log('get Oplog success:', response); table.init; btn.button; btn.dequeue(); }, function errorCallback { console.log('errorCallback Response is:', response); table.init(); btn.button; btn.dequeue;};

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

本文由澳门娱乐6165发布,转载请注明来源

关键词: