angularjs之$ajax請求


AngularJS不僅僅只有雙向綁定等等功能,還有發送Ajax請求的Api。

效果圖:

請求的文件(data.php):

<?php $data = [ '股市下跌', '清明小長假結束', '我要接着學習了' ]; echo json_encode($data);

Jqurey方式

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>使用jquery加載網絡數據</title> </head> <script src="http://cdn.bootcss.com/jquery/3.2.0/jquery.min.js"></script> <body> <h1>使用jquery加載網絡數據</h1> <ul> <li></li> <li></li> <li></li> </ul> </body> <script> $.get('data.php',function(rs){ var i = 0; $('li').each(function(){ this.innerHTML = rs[i++]; }); },'json'); </script> </html>

AngularJS方式

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>使用Angular加載網絡數據</title> </head> <script src="//cdn.bootcss.com/angular.js/1.6.3/angular.min.js"></script> <body> <h1>使用Angular加載網絡數據</h1> <ul ng-app="news" ng-controller="con"> <li ng-repeat="n in news">{{n}}</li> </ul> </body> <script> var app = angular.module('news',[]); app.controller('con',function($scope,$http){ $http({ method:'GET', url:'data.php', }).then(function successCallback (rs){ $scope.news = rs.data; }); }); </script> </html>

使用JQuery中的Ajax和使用AngularJS中的Ajax本質上沒有區別,只是api的區別,但是獲取數據之后,jquery方式必須自己寫操作dom元素的代碼,但是AngularJS中就不用手動寫操作dom元素的代碼,而只是用一個ng-repeat標簽來操作dom,換句話說,AngularJS操作dom的代碼已經被封裝起來了,我們不用寫,而jquery中必須寫。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM