angularjs php 项目实例,angularJs中$http获取后台数据的实例讲解

1.html

网站名称网址
{{v.name}}{{v.url}}

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);

});

}]);

1.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数据的几种方式:

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);

})

}]);

#第一种处理方法

//$content = file_get_contents('php://input');

//print_r(json_decode($content,true));

#第二种方式

print_r($_POST);

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值