AngularJS中$http使用的简单介绍

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

AngularJS中$http使用的简单介绍

EldonZhao   2020-05-15 我要评论

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

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

$http使用说明:

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

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

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

具体参数、方法说明:

配置参数:

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

回调函数:

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

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

$http.post(url, data, config)

$http使用范例:

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们