国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

angularJs中$http獲取后臺數據的實例講解

2019-11-19 13:19:13
字體:
來源:轉載
供稿:網友

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

<?php$data = [ [ 'name' => '百度', 'url' => 'www.baidu.com' ], [ 'name' => '騰訊', 'url' => 'www.qq.com' ],];echo json_encode($data,JSON_UNESCAPED_UNICODE);

上面是最簡單的$http獲取后臺數據實例,假如一個頁面中要異步加載一個后臺文件好幾次,那么是不是也要請求服務好幾次呢?顯然這樣會使頁面的加載出現遲鈍,那么,我們可以通過緩存操作來減少服務器壓力,使其盡快顯示頁面數據,那么,具體怎么做呢?很簡單,在$http 中添加cache:true, ,即可解決,再刷新頁面的時候,只會顯示一次重復請求的數據。

  $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獲取后臺數據的實例講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 日照市| 定兴县| 扎囊县| 莱州市| 丁青县| 乌苏市| 佛山市| 湖南省| 鄯善县| 阿勒泰市| 汾西县| 徐汇区| 兴国县| 青岛市| 额尔古纳市| 射洪县| 微山县| 临城县| 鸡东县| 萨嘎县| 兴城市| 弥勒县| 静海县| 邛崃市| 酒泉市| 东城区| 哈尔滨市| 滨州市| 张家界市| 财经| 大同市| 邮箱| 清远市| 辉县市| 仪征市| 马边| 伊春市| 铁岭县| 伊川县| 白玉县| 台中县|