經過jquery的ajax請求本地的json文件

本身學習jquery的ajax的經歷,記錄一下html

ajaxTestDemo.html jquery

在body裏面放一個id爲test的divajax

<div id="test"></div>json

第一步仍是要先加載jquery文件 jquery.min.js安全

<script>
    $(function(){
            $.ajax({
            //請求方式爲get
            type:"GET",
            //json文件位置
            url:"./data/shuju.json",
            //返回數據格式爲json
            dataType: "json",
            //請求成功完成後要執行的方法
            success: function(data){
                //使用$.each方法遍歷返回的數據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文件app

{
  "list":[
    {"item":"審計管理"},
    {"item":"菜單管理"},
    {"item":"訂單管理"},
    {"item":"合同管理"},
    {"item":"物流管理"},
    {"item":"行政管理"},
    {"item":"人事管理"},
    {"item":"購物管理"},
    {"item":"批發管理"},
    {"item":"安全管理"},
    {"item":"帳號管理"},
    {"item":"財務管理"},
    {"item":"其餘管理"}
  ]
}
/* json文件里居然不能有這樣的註釋,由於困擾了幾個小時!*/


完整的頁面代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>測試jqueyajax方法</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",
            //返回數據格式爲json
            dataType: "json",
            //請求成功完成後要執行的方法
            success: function(data){
                //使用$.each方法遍歷返回的數據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);
    });
});

天天積累一點點,本身會的走的更遠!測試