AngularJs中的$http服务实现前端与后端之间的数据传输,与JQuery中的ajax类似,具体代码如下:
1、接收后端数据:
需要用到的php代码,文件名为1.php:
2 | header( 'Content-type:text/html;charset="utf-8"' ); |
5 | array ( 'webname' => '赵一鸣个人技术博客' , 'weburl' => 'http://www.zymseo.com' ), |
6 | array ( 'webname' => '太原雅辉装修网' , 'weburl' => 'http://www.0351zhuangxiu.com' ) |
9 | echo json_encode( $arry ); |
|
前端代码:
1 | var m = angular.module( 'app' , []); |
2 | m.controller( 'ctr2' , [ '$scope' , '$http' , function ($scope, $http){ |
6 | }).then( function (result){ |
|
打印结果如下:
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){ |
11 | }).then( function (result){ |
|
后端PHP代码:
2 | header( 'Content-type:text/html;charset="utf-8"' ); |
6 | print_r(json_decode( $content , true)); |
|
注意:用PHP接受AnguarJs传输的数据时,需要用到file_get_contents这个方法,然后参数是'php://input',这样才能正常解析使用。