Posted in jQuery onJanuary 28, 2019
本文实例讲述了jQuery访问json文件中数据的方法。分享给大家供大家参考,具体如下:
有时候我们可能需要用到json文件存储数据,然后通过前台语言直接进行访问。
首先是json文件:
{ "管道": [ { "ElementId": "标识号", "GISID": "GISID", "Label": "编号", "StartNodeID":"起始节点ID", "EndNodeID":"终止节点ID", "StartNodeLabel":"起始节点编号", "EndNodeLabel":"终止节点编号", "Physical_PipeDiameter":"管径", "Physical_PipeMaterialID":"管材", "Physical_HazenWilliamsC":"海曾威廉C值", "Physical_Length":"管长", "Physical_MinorLossCoefficient":"局部阻力系数", "Physical_InstallationYear":"铺设年代", "Physical_Address":"地址", "District":"营销公司", "DMA":"计量区", "Zone":"行政区", "flow":"当前流量", "velocity":"当前流速", "headloss":"当前水头损失" }], "节点": [{ "ElementId": "标识号", "GISID": "GISID", "Label": "编号", "Physical_Elevation":"地面高程", "Physical_Depth":"埋深", "Physical_Address":"地址", "District":"营销公司", "DMA":"计量区", "Zone":"行政区", "hydraulicGrade":"水压标高", "pressure":"自由水压", "demand":"节点流量", "cl":"余氯浓度", "age":"水龄", "source":"供水水源" }], "阀门": [{ "ElementId": "标识号", "GISID": "GISID", "Label": "编号", "Physical_Elevation":"地面高程", "Physical_Depth":"埋深", "Physical_Diameter":"口径", "Physical_Status":"阀门状态", "Physical_Address":"地址", "District":"营销公司", "DMA":"计量区", "Zone":"行政区", "Physical_InstallationYear":"安装年代" }], "水表": [{ "DIAMETER":"口径", "CALIBER": "表径", "MATERIAL": "材质", "DEPTH":"埋深", "HEIGHT":"地面高程", "ADDR":"地址", "WATREGID": "表号", "USERNAME":"用户名", "JUNCTION":"接口类型", "DISTRICT":"行政区", "MEASUREIN":"营销公司", "FINISHDATE":"安装日期" }], "消火栓": [{ "ElementId": "标识号", "GISID": "GISID", "Label": "编号", "Physical_Elevation":"地面高程", "Physical_Depth":"埋深", "Physical_Address":"地址", "District":"营销公司", "DMA":"计量区", "Zone":"行政区", "Physical_Diameter":"口径", "Physical_Type":"样式" }] }
创建CriteriaQuery.json文件,文件内容如上。
前台代码:
<html> <head> <meta charset="GBK"/> <title>jQuery访问json</title> <script type="text/javascript" src="https://libs.baidu.com/jquery/1.4.0/jquery.min.js"></script> <script type="text/javascript"> $(function (){ $("#btn").click(function(){ $.getJSON("CriteriaQuery.json",function(data){ var $jsontip = $("#jsonTip"); var strHtml = ""; $jsontip.empty(); $.each(data.管道,function(infoIndex,info){ for(var o in info){ strHtml +=info[o]; } //strHtml +=info["ElementId"]; }); $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>
我这里的jquery用的1.4.0版本的js文件,即https://libs.baidu.com/jquery/1.4.0/jquery.min.js
json文件与html放在同一个目录下。
运行代码,点击获取数据按钮,就能够在页面上看到遍历json文件所得到的“管道”的所有信息。当然,也可以通过key来获取到json文件的value,即
strHtml +=info["ElementId"];
感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.3water.com/code/HtmlJsRun测试上述代码运行效果。
jQuery访问json文件中数据的方法示例
- Author -
kaleid_liner声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@