您的位置:首页 > 理论基础 > 计算机网络

AngularJs之$http服务前端与后端之间的数据传输

2018-02-08 13:58 555 查看
AngularJs中的$http服务实现前端与后端之间的数据传输,与JQuery中的ajax类似,具体代码如下:1、接收后端数据:需要用到的php代码,文件名为1.php:
1
<?php
2
    
header(
'Content-type:text/html;charset="utf-8"'
);
3
 
4
    
$arry
 
array
(
5
        
array
(
'webname'
=>
'赵一鸣个人技术博客'
'weburl'
=>
'http://www.zymseo.com'
),
6
        
array
(
'webname'
=>
'太原雅辉装修网'
'weburl'
=>
'http://www.0351zhuangxiu.com'
)
7
    
);
8
 
9
    
echo
 
json_encode(
$arry
);
前端代码:
1
var
 
m = angular.module(
'app'
, []);
2
m.controller(
'ctr2'
, [
'$scope'
'$http'
function
($scope, $http){
3
    
$http({
4
        
'url'
 
'./1.php'
,
5
        
'method'
 
'post'
6
    
}).then(
function
(result){
7
        
console.log(result);
8
    
});
9
}]);
打印结果如下:
1
Object { data: Array[2], status: 200, headers: bd/<(), config: Object, statusText: 
"OK"
 
}
最后解析对象的data属性,就可以得到我们需要的数据!2、向后端发送数据:前端代码:
01
var
 
m = angular.module(
'app'
, []);
02
m.controller(
'ctr2'
, [
'$scope'
'$http'
function
($scope, $http){
03
    
$http({
04
        
'url'
 
'./1.php'
,
05
        
'method'
 
'post'
,
06
        
'data'
 
: {
07
            
'name'
 
'赵一鸣'
,
08
            
'sex'
 
'男'
,
09
            
'work'
 
'WEB前端开发'
10
        
}
11
    
}).then(
function
(result){
12
        
console.log(result);
13
    
});
14
}]);
后端PHP代码:
1
<?php
2
    
header(
'Content-type:text/html;charset="utf-8"'
);
3
 
4
    
$content
 
file_get_contents
(
'php://input'
);
5
    
 
6
    
print_r(json_decode(
$content
, true));
注意:用PHP接受AnguarJs传输的数据时,需要用到file_get_contents这个方法,然后参数是'php://input',这样才能正常解析使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: