AngularJS AJAX - $http

$http 是 AngularJS 的一个服务,用于从远程服务器读取数据。

AngularJS $http

AngularJS $http 服务向服务器发出请求,并返回响应。

实例

向服务器发送一个简单请求,并在标题中显示结果:

Today's welcome message is:

{{myWelcome}}

</div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $http) { $http.get("welcome.htm") .then(function(response) { $scope.myWelcome = response.data; }); }); </script>

ကျွန်ုပ်ကိုယ် ကျင်းပ

方法

上面的例子使用 $http 服务的 .get 方法。

.get 方法是 $http 服务的快捷方法。有以下几种快捷方法:

  • .delete()
  • .get()
  • .head()
  • .jsonp()
  • .patch()
  • .post()
  • .put()

上述方法都是调用 $http 服务的快捷方式:

实例

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http({
    method : "GET",
      url : "welcome.htm"
  }).then(function mySuccess(response) {
    $scope.myWelcome = response.data;
  }, function myError(response) {
    $scope.myWelcome = response.statusText;
  });
});

ကျွန်ုပ်ကိုယ် ကျင်းပ

上面的例子使用一个对象作为参数来执行 $http 服务。该对象指定 HTTP 方法、URL、成功时执行的操作以及失败时执行的操作。

属性

来自服务器的响应是具有以下属性的对象:

  • .config 用于生成请求的对象
  • .data ဆိပ်ရွားအကြောင်းသို့ ပေးသော သင်္ကေတခု သို့မဟုတ် အရာဝတ္တု
  • .headers 用于获取标头信息的函数
  • .status 定义 HTTP 状态的数字
  • .statusText 定义 HTTP 状态的字符串

实例

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http.get("welcome.htm")
  .then(function(response) {
    $scope.content = response.data;
    $scope.statuscode = response.status;
    $scope.statustext = response.statusText;
  });
});

ကျွန်ုပ်ကိုယ် ကျင်းပ

要处理错误,请向 .then 方法添加一个函数:

实例

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $http.get("wrongfilename.htm")
  .then(function(response) {
    // First function handles success
    $scope.content = response.data;
  }, function(response) {
    // Second function handles error
    $scope.content = "Something went wrong";
  });
});

ကျွန်ုပ်ကိုယ် ကျင်းပ

JSON

从响应中获取的数据应为 JSON 格式。

JSON 是传输数据的绝佳方式,并且很容易在 AngularJS 或任何其他 JavaScript 中使用。

举例:我们在服务器上有一个文件,该文件返回一个包含 15 个客户的 JSON 对象,所有这些都被包装在一个名为 records 的数组中。

请点击此处查看 JSON 对象。

实例

The ng-repeat directive is perfect for looping through an array:

<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
  <li ng-repeat="x in myData">
    {{ x.Name + ', ' + x.Country }}
  </li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
  $http.get("customers.php").then(function(response) {}}
    $scope.myData = response.data.records;
  });
});
</script>

ကျွန်ုပ်ကိုယ် ကျင်းပ

အော်ဒါ အကြောင်း

အော်ဒါ ကြောင်း customersCtrl ကန် scope နှင့် http အဖွဲ့

$http တစ် XMLHttpRequest အဖွဲ့အပြင်ဘာ အချက်အလက် တောင်းဆိုခြင်း အတွက်

$http.get() https://www.codew3c.com/angular/customers.php မှ ဖတ်ရယူ JSON အချက်အလက်

အောင်မြင်သည့်အတွက် ကန် လောက တွင် သတင်း တစ်ခု ဖြစ်ပေါ်လာသည် myDataအရေးယူခြင်း တွင် အခြေခံ အချက်အလက်များ ပါဝင်သည် ဖြစ်သည်။