jquery读取json文件

Javascript piniu 979浏览 0评论

json文件是一种轻量级的数据交互格式。一般在jquery中使用getJSON()方法读取。

$.getJSON(url, [data], [callback])

url:加载的页面地址 
data: 可选项,发送到服务器的数据,格式是key/value 
callback: 可选项,加载成功后执行的回调函数

具体使用实例参照如下:
1.首先建一个JSON格式的文件userinfo.json 保存用户信息。

[
   {
		"name": "张国立",
		"sex": "男",
		"email": "zhangguoli@123.com"
	},
	{
		"name": "张铁林",
		"sex": "男",
		"email": "zhangtieli@123.com"
	},
	{
		"name": "邓婕",
		"sex": "女",
		"email": "zhenjie@123.com"
	}
]

2. 其次建一个页面用于获取JSON文件里的用户信息数据,并显示 。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>getJSON获取数据</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
    <style type="text/css">
        #divframe{ border:1px solid #999; width:500px; margin:0 auto;}
        .loadTitle{ background:#CCC; height:30px;}
    </style>
 
    <script type="text/javascript">
        $(function (){
            $("#btn").click(function () {
                //获取json文件数据
                $.getJSON("js/userinfo.json", function (data){
                    var jsontip = $("#jsonTip");
                    var strHtml = "";
                    //存储数据的变量
                    jsontip.empty();
                    //清空内容
                    $.each(data, function (infoIndex, info){
                        strHtml += "姓名:" + info["name"] + "<br>";
                        strHtml += "性别:" + info["sex"] + "<br>";
                        strHtml += "邮箱:" + info["email"] + "<br>";
                        strHtml += "<hr>"
                    })
                    jsontip.html(strHtml);
                    //显示处理后的数据
                })
            })
        })
    </script>
    </head>
<body>
    <div id="divframe">
        <div class="loadTitle">
            <input type="button" value="获取数据" id="btn"/>
        </div>
        <div id="jsonTip">
    </div>
</div>
</body>
</html>

附:Ajax获取json文件数据,这里只粘贴js代码了

<script type="text/javascript">
		$(function () {
			$.ajax({
			  type: "POST",
			  dataType: "json",
			  url: "js/userinfo.json",
			  success: function (result) {
					var jsontip = $("#jsonTip");
					var strHtml = "";
					//存储数据的变量
					jsontip.empty();
					//清空内容
					$.each(data, function (infoIndex, info){
						strHtml += "姓名:" + info["name"] + "<br>";
						strHtml += "性别:" + info["sex"] + "<br>";
						strHtml += "邮箱:" + info["email"] + "<br>";
						strHtml += "<hr>"
					})
					jsontip.html(strHtml);
					//显示处理后的数据
			  }
			});
		});
    </script>
 

发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • * 昵称:
  • * 邮箱: