清華大佬耗費三個月吐血整理的幾百G的資源,免費分享!....>>>
AngularJS XMLHttpRequest
$http 是 AngularJS 中的一個核心服務(wù),用于讀取遠程服務(wù)器的數(shù)據(jù)。
讀取 JSON 文件
以下是存儲在web服務(wù)器上的 JSON 文件:
http://www.wangchenghua.com/try/angularjs/data/sites.php
{ "sites": [ { "Name": "菜鳥教程", "Url": "www.wangchenghua.com", "Country": "CN" }, { "Name": "Google", "Url": "www.google.com", "Country": "USA" }, { "Name": "Facebook", "Url": "www.facebook.com", "Country": "USA" }, { "Name": "微博", "Url": "www.weibo.com", "Country": "CN" } ] }AngularJS $http
AngularJS $http 是一個用于讀取web服務(wù)器上數(shù)據(jù)的服務(wù)。
$http.get(url) 是用于讀取服務(wù)器數(shù)據(jù)的函數(shù)。
AngularJS 實例
<div ng-app="myApp" ng-controller="siteCtrl"> <ul> <li ng-repeat="x in names"> {{ x.Name + ', ' + x.Country }} </li> </ul> </div> <script> var app = angular.module('myApp', []); app.controller('siteCtrl', function($scope, $http) { $http.get("http://www.wangchenghua.com/try/angularjs/data/sites.php") .success(function (response) {$scope.names = response.sites;}); }); </script>應(yīng)用解析:
注意:以上代碼的 get 請求是本站的服務(wù)器,你不能直接拷貝到你本地運行,會存在跨域問題,解決辦法就是將 Customers_JSON.php 的數(shù)據(jù)拷貝到你自己的服務(wù)器上,附:PHP Ajax 跨域問題最佳解決方案。
AngularJS 應(yīng)用通過 ng-app 定義。應(yīng)用在 <div> 中執(zhí)行。
ng-controller 指令設(shè)置了 controller 對象 名。
函數(shù) customersController 是一個標準的 JavaScript 對象構(gòu)造器。
控制器對象有一個屬性: $scope.names。
$http.get() 從web服務(wù)器上讀取靜態(tài) JSON 數(shù)據(jù)。
服務(wù)器數(shù)據(jù)文件為:? http://www.wangchenghua.com/try/angularjs/data/sites.php。
當從服務(wù)端載入 JSON 數(shù)據(jù)時,$scope.names 變?yōu)橐粋€數(shù)組。
![]() |
以上代碼也可以用于讀取數(shù)據(jù)庫數(shù)據(jù)。 |
---|
掃碼二維碼 獲取免費視頻學(xué)習(xí)資料