ng $http 和远程服务器通信的一个服务。

$http({url:'',method:''}).success().error()

简洁写法:
$http.get()
$http.post()
...

注意事项:
①要求返回的数据格式是json格式
②在发起post请求时,如果需要传参
$http.post('url',data),需要设置请求头:
$http.defaults.headers.post = {'Content-Type':'application/x-www-form-urlencoded'};

全局设置请求头:
app.run(function($http){
$http.defaults.headers.post = {'Content-Type':'application/x- www-form-urlencoded'};})

 

 

例子:

点击按钮,发起get请求,服务器接收数据返回给客户端,将返回的结果显示出来
发送:name='zhangsan'
返回:json格式字符串
tip:welcome zhangsan

 

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
  <meta charset="UTF-8">
  <script src="js/angular.js"></script>
  <title></title>
</head>
<body>
<div ng-controller="myCtrl">
  <button ng-click="getData()">
    get请求
  </button>
  <ul>
    <li ng-repeat="tmp in list">
      {{"name is "+tmp.name+" age is "+tmp.age}}
    </li>
  </ul>
</div>
<script>
  var app = angular.module('myApp', ['ng']);
  app.controller('myCtrl',
    function ($scope,$http) {
        $scope.list = [];
        $scope.getData = function () {
          $http
            .get('data/test.json')
            .success(function (result) {
              $scope.list = result;
            })
            .error(function () {
              console.log(arguments);
            })
        }
    })
</script>
</body>
</html>

 

其中 test.json:

[
  {
    "name":"Lucy",
    "age":20
  },
  {
    "name":"Lily",
    "age":21
  },
  {
    "name":"Mary",
    "age":23
  }
]

 

2.

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
  <meta charset="UTF-8">
  <script src="js/angular.js"></script>
  <title></title>
</head>
<body>
<div ng-controller="myCtrl">
  <button ng-click="postData()">
    获取信息
  </button>
  <span>{{msg.tip}}</span>
</div>
<script>
  var app = angular.module('myApp', ['ng']);

  //全局设置 post请求头
  //app.config 需要用到provider
  //app.run

  app.run(function ($http) {
    $http.defaults.headers.post = {
      'Content-Type':
        'application/x-www-form-urlencoded'
    }}
    );

  app.controller('myCtrl',
    function ($scope,$http,$httpParamSerializerJQLike) {
      $scope.postData = function () {
        var user =
        {name:'zhangsan',age:20,score:90};
        var result =
          $httpParamSerializerJQLike(user);
        console.log(result);
        $http
          .post('data/test.php',result)
          .success(function (data) {
            console.log(data);
            $scope.msg = data;
          })
      }
    })
</script>
</body>
</html>

其中test.php:

 

<?php

header("Content-Type:application/json");

@$name = $_REQUEST['name'];

$result = [];
$result = [
'tip'=> 'welcome '.$name
];

echo json_encode($result);

?>

 

posted @ 2017-06-07 20:25  快乐的咸鱼  阅读(496)  评论(0编辑  收藏  举报