通過jquery的ajax請求本地的json文件方法
自己學習jquery的ajax的經(jīng)歷,記錄一下
ajaxTestDemo.html
在body里面放一個id為test的div
<div id="test"></div>
第一步還是要先加載jquery文件 jquery.min.js
<script>
$(function(){
$.ajax({
//請求方式為get
type:"GET",
//json文件位置
url:"./data/shuju.json",
//返回數(shù)據(jù)格式為json
dataType: "json",
//請求成功完成后要執(zhí)行的方法
success: function(data){
//使用$.each方法遍歷返回的數(shù)據(jù)date,插入到id為#result中
var str="<ul>";
$.each(data.list,function(i,n){
str+="<li>"+n["item"]+"</li>";
})
str+="</ul>";
$("#test").append(str);
}
});
});
</script>
shuju.json文件
{
"list":[
{"item":"審計管理"},
{"item":"菜單管理"},
{"item":"訂單管理"},
{"item":"合同管理"},
{"item":"物流管理"},
{"item":"行政管理"},
{"item":"人事管理"},
{"item":"購物管理"},
{"item":"批發(fā)管理"},
{"item":"安全管理"},
{"item":"賬號管理"},
{"item":"財務(wù)管理"},
{"item":"其他管理"}
]
}
/* json文件里竟然不能有這樣的注釋,因為困擾了幾個小時!*/
完整的頁面代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>測試jquey的ajax方法</title>
<style>
*{
padding:0;
margin:0;
}
#test{
padding: 0;
margin: 0 auto;
width:200px;
height: 400px;
}
#test li{
list-style: none;
width:200px;
text-align: center;
height:30px;
line-height:30px;
border:1px dashed lightgrey;
}
</style>
</head>
<body>
<div id="test"></div>
<script src="js/jquery.min.js"></script>
<script>
$(function(){
alert(1);
$.ajax({
//請求方式為get
type:"GET",
//json文件位置
url:"./data/shuju.json",
//返回數(shù)據(jù)格式為json
dataType: "json",
//請求成功完成后要執(zhí)行的方法
success: function(data){
//使用$.each方法遍歷返回的數(shù)據(jù)date,插入到id為#result中
var str="<ul>";
$.each(data.list,function(i,n){
str+="<li>"+n["item"]+"</li>";
})
str+="</ul>";
$("#test").append(str);
}
});
});
</script>
</body>
</html>
還可以通過$.getJSON來獲取本地json文件
/* getJSON*/
$(function(){
$.getJSON("./data/shuju.json",function(data){
var str="<ul>";
$.each(data.list,function(i,n){
str+="<li>"+n["item"]+"</li>";
})
str+="</ul>";
$("#test").append(str);
});
});
以上這篇通過jquery的ajax請求本地的json文件方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
jQuery實現(xiàn)轉(zhuǎn)動隨機數(shù)抽獎效果的方法
這篇文章主要介紹了jQuery實現(xiàn)轉(zhuǎn)動隨機數(shù)抽獎效果的方法,涉及jQuery操作隨機數(shù)及頁面元素的相關(guān)技巧,需要的朋友可以參考下2015-05-05
jQuery setTimeout傳遞字符串參數(shù)報錯的解決方法
這篇文章主要介紹了jQuery setTimeout傳遞字符串參數(shù)報錯的解決方法,需要的朋友可以參考下2014-06-06
根據(jù)郵箱的域名跳轉(zhuǎn)到相應(yīng)的登錄頁面的代碼
其實主要是想記錄一下這種對象的用法,喜歡的朋友可以參考下2012-02-02
jquery easyui dataGrid動態(tài)改變排序字段名的方法
jQuery easyui dataGrid 動態(tài)改變排序字段名,一般情況下,在使用的時候,我們會點擊相應(yīng)字段進行排序。今天小編以java為例給大家講解問題原因及解決方案,需要的的朋友參考下2017-03-03
jQuery簡單實現(xiàn)點擊文本框復(fù)制內(nèi)容到剪貼板上的方法
這篇文章主要介紹了jQuery簡單實現(xiàn)點擊文本框復(fù)制內(nèi)容到剪貼板上的方法,涉及jQuery針對瀏覽器的判定與剪貼板的讀寫操作技巧,需要的朋友可以參考下2016-08-08

