使用jquery从后台获取JSON数据,显示
知识点:
使用了require JS 框架
用Jquery的两种方法获取后台数据
1)ajax 方法,传回的都是json数据
2)getJSON, 直接封装了一些参数{command : GetRegsiterJsonData}
代码:
test.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <!DOCTYPE html> <head> <title>MyWebProject</title> <meta charset="utf-8" /> <link type="text/css" href="./lib/css/jquery-ui-1.8.19.custom.css" rel="stylesheet" /> <script type="text/javascript" src="./lib/js/require-jquery.js" data-main="js/main"> </script>
</head> <body> <label id="dataArea"></label> </body> </html>
|
main.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| var loadJS = [ "jquery", ];
require.config({ baseUrl : "lib/js/", paths: { "jquery": "jquery-1.8.3.min", } });
//Function In main require(loadJS, LoadData("./Test"));
//CallWebTrendsUri function LoadData(url){ $(function(){ $(document).ready(function(){ jQuery.ajax({ type:"GET", url: url + "?command=GetRegsiterJsonData", dataType:"json", global:false, success: function(data){ var jsonData = "1. 用统一的ajax方法<br/>"; var personList = data.personList; for(var i=0; i<personList.length; i++){ var name = personList[i].name; var age = personList[i].age; jsonData += "name: " + name + ", age: " + age + "<br/>"; } $("#dataArea").html(jsonData + "<br/>"); } }); $.getJSON(url, {command: "GetRegsiterJsonData"}, function(data){ var jsonData = "2. 用getJSON方法<br/>"; var personList = data.personList; $.each(personList, function(i){ var name = personList[i].name; var age = personList[i].age; jsonData += "name: " + name + ", age: " + age + "<br/>"; }); $("#dataArea").html($("#dataArea").html() + jsonData); }); }); }); };
|
JSON数据如下:
1
| {"time":"2012/12/16","personList":[{"name":"Jeremy","age":20},{"name":"Tom","age":43},{"name":"Mary","age":33}]}
|