angular https get&post 请求整理

静态html页面,底部是服务端返回json数据!
angular js 中https get 和 post 请求,分别作了处理和整合,希望对初学的你有所帮助,少采一些坑
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>

<div ng-app="myApp" ng-controller="arrList">
    <h1 align="center">angular https get&post request!</h1>
    <h2>ajax get  requeset:</h2>

    <h3>{{ showName }}</h3>
    <ul>
        <li ng-repeat="x in cateList">
            {{ x.id + ' >> ' + x.name }}
        </li>
    </ul>
    <br><hr><br>
    <h2>ajax post  requeset:</h2>
    <ul>
        <li ng-repeat="x in cate">
            {{ x.id + ' >> ' + x.name }}
        </li>
    </ul>

</div>

<script type="text/javascript">
    var url = "angular.php";
    var app = angular.module('myApp', []);
    app.controller('arrList', function($scope, $http) {
//    then方法,默认数据放回带,data
//        todo get 请求 , ps :{params:{ json数据 }}
        var get_data = {params: {name:'get_data',id:1}};
        $http.get(url, get_data).then(function (res) {
            $scope.showName = res.data;
            if (res.data.code == 1) {
                $scope.cateList = res.data.msg;
            } else {
                alert("request error!");
                return false;
            }
        });

//       todo post请求
        $http({
            method: "POST",
            url: url,
            data: {name:'post_data',id:2}, //json数据
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, //修改http header 请求类型,post所用
            transformRequest: function(response) {
                var res = [];
                for (var i in response) {
                    res.push(encodeURIComponent(i) + "=" + encodeURIComponent(response[i]));
                }
                return res.join("&");
            }
        }).success(function(res){
            $scope.cate = res.msg;
        }).error(function(res){
            alert('error!');
        })

    });
</script>

</body>
</html>

 

文件:angular.php
<?php if ($_POST) { $rep[] = $_POST; } else { $rep[] = $_GET; } // return {"msg":[{"id":"1","name":"get_data"}],"code":1} json数据类型 print_r(json_encode(array('msg'=>$rep,'code'=>1)));

 

posted @ 2017-01-12 18:45  LoveProgram  阅读(905)  评论(0编辑  收藏  举报