网络编程 
首页 > 网络编程 > 浏览文章

angularJs中$http获取后台数据的实例讲解

(编辑:jimmy 日期: 2025/3/18 浏览:3 次 )

1.html

<div ng-app="module" ng-controller="ctrl">
 <table border="1" width="600">
  <tr>
   <td>网站名称</td>
   <td>网址</td>
  </tr>
  <tr ng-repeat="v in data">
   <td>{{v.name}}</td>
   <td>{{v.url}}</td>
  </tr>
 </table>
</div>
<script>
 var m = angular.module('module', []);
 //注入http服务
 m.controller('ctrl', ['$scope', '$http', function ($scope, $http) {
  $http({
   method:'get', //get请求方式
   url:'1.php' //请求地址
  }).then(function(response){
   //成功时执行
   console.log(response);
   $scope.data = response.data; //得到请求的数据
  },function(response){
   //失败时执行 
   console.log(response);
  });
 }]);
</script>

1.php

<"htmlcode">
  $http({
   method:'get',
   url:'1.php',
   cache:true, //避免多次请求后台数据
  }).then(function(response){
   //成功时执行
   console.log(response);
   $scope.data = response.data;
  },function(response){
   //失败时执行 
   console.log(response);
  });

当然,像jquery的ajax请求那样,angularjs也可以进行简写,

 m.controller('ctrl', ['$scope', '$http', function ($scope, $http) {
 //post方式
 //$http.post('1.php',{id:1})参数里可加属性
  $http.post('1.php').then(function(response){
   //成功时执行
   console.log(response);
   $scope.data = response.data;
  });
 }]);
 m.controller('ctrl', ['$scope', '$http', function ($scope, $http) {
 //get方式
 //$http.get('1.php',{cache:true}) 参数里可加属性
  $http.get('1.php').then(function(response){
   //成功时执行
   console.log(response);
   $scope.data = response.data;
  });
 }]);

最后,来说下 $http服务之后台接收POST数据的几种方式:

<div ng-app="module" ng-controller="ctrl"></div>
<script>
 var m = angular.module('module', []);
 m.controller('ctrl', ['$scope', '$http', function ($scope, $http) {
  //第一种方式
/*  $http({
   method:'post',
   url:'1.php',
   data:{id:1,name:'后盾人'}
  }).then(function(response){
   console.log(response.data);
  })*/
 //第二种方式
  $http({
   method:'post',
   url:'1.php',
   data:$.param({id:1,name:'后盾人'}),
   headers:{'Content-type':'application/x-www-form-urlencoded'}
  }).then(function(response){
   console.log(response.data);
  })
 }]);
</script>
<?php
#第一种处理方法
//$content = file_get_contents('php://input');
//print_r(json_decode($content,true));

#第二种方式
print_r($_POST);

以上这篇angularJs中$http获取后台数据的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:微信小程序wepy框架笔记小结
下一篇:JavaScript常见JSON操作实例分析
一文看懂荣耀MagicBook Pro 16
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?