一、JQuery與AngularJS
首先,先簡單的了解一下JQuery與AngularJS。從源頭上來說,兩者都屬於原生JS所封裝成的庫,兩種為平行關系。
二、Ajax請求與數據遍歷打印
這里是Ajax和$http請求的JSON文件概覽,默認的路徑我們就放在與兩者同級的文件夾里。
[ { "name": "一號", "age": 17, "hobby": [ "吃", "喝" ], "score":{ "math":78, "chinese":89 } }, { "name": "二號", "age": 17, "hobby": [ "喝", "玩" ], "score":{ "math":78, "chinese":89 } }, { "name": "三號", "age": 17, "hobby": [ "玩", "樂" ], "score":{ "math":78, "chinese":89 } }, { "name": "四號", "age": 17, "hobby": [ "吃", "喝", "玩", "樂" ], "score":{ "math":78, "chinese":89 } } ]
下面是Ajax請求獲取JSON文件的代碼。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Ajax</title> <script language="JavaScript" src="js/jquery-1.10.2.js"></script> <script type="text/javascript"> $(function(){ $("button").click(function(){ $.ajax({ type:"post", url:"http://localhost:8080/JSON/h51701.json", dataType:"JSON", success:function(data){ console.log(data) } }); }) </script> </head> <body> <button>點擊請求JSON文件</button> <div></div> </body> </html>
如果想要直接遍歷取出JSON文件中的各種值,則可以通過post和get,一般我們所用的是post,使用時,只需要吧$ajax這一部分換成以下代碼。
$.post("http://localhost:8080/JSON/h51701.json",{},function(data){ for(var i = 0 ; i < data.length ; i++){ $("div").append("姓名:"+data[i].name+"<br />"); $("div").append("年齡:"+data[i].age+"<br />"); $("div").append("數學成績:"+data[i].score.math+"<br />"); $("div").append("語文成績:"+data[i].score.chinese+"<br />"); $("div").append("愛好:"+data[i].hobby.toString()+"<br /><br />"); } },"json")
在這里,我們一般是采用循環遍歷的方法一一取出。
三、$http請求與數據的提取
相較而言,$http的方法更簡單粗暴,代碼如下。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>$http</title> </head> <body ng-app="app" ng-controller="ctrl"> <pre>{{data}}</pre> <table> <thead> <tr> <th>姓名</th> <th>年齡</th> <th>喜好</th> <th>數學成績</th> <th>語文成績</th> <th>總分</th> </tr> </thead> <tr ng-repeat="item in data | orderBy:'score.chinese'"> <td ng-bind="item.name"></td> <td ng-bind="item.age"></td> <td ng-bind="item.hobby"></td> <td ng-bind="item.score.chinese"></td> <td ng-bind="item.score.math"></td> <td ng-bind="item.score.chinese + item.score.math"></td> </tr> </table> </body> <script src="libs/angular.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> angular.module("app", []) .controller("ctrl", function($scope,$http) { //方法一 $http({ method: 'POST', url: 'h51701.json' }).then(function successCallback(response) { // 請求成功執行代碼 $scope.res = response; }, function errorCallback(response) { // 請求失敗執行代碼 alert("服務請求失敗") }); //方法二 $http.get("h51701.json").then(function successFunction(a){ $scope.res = a; }) //方法三 $http.post("h51701.json",{/*傳遞的參數對象*/}).then(function successFunction(a){ $scope.data = a.data;//從返回的信息中取出需要的數據,為JSON對象(數組) }) }) </script> </html>
在請求方面,三種方法大致與ajax相同,但是在每一數據的提取方面,AngularJS所提供的ng-repeat提供了非常大的便利。
綜上,兩者相比較,還是AngularJS提取更方便。但是從現如今的更新上講,JQuery中的ajax更加穩定。