json在前端的运用

来源:互联网 发布:谷歌娘语音软件 编辑:程序博客网 时间:2024/05/17 09:16

一:json是什么?

JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。它基于 ECMAScript (w3c制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

二:前端接受后台传过来的json数据

代码示例:

<html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'goodsList.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page">  <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>  <script type="text/javascript">  window.onload=function(){  var all = document.getElementById('all');  all.onclick=function(){
<!-- 调用ajax请求,访问成功接受json数据 -->
  $.post("selectAll_good",function(Result){  var name = document.getElementById('name'),  main = document.getElementById('main'),  goodTitle = document.getElementById('goodTitle'),  goodMessage = document.getElementById('goodMessage'),  goodPicture = document.getElementById('goodPicture'),  goodPrice = document.getElementById('goodPrice'),  goodId = document.getElementById('goodId'),
    <!-- 得到json数据,讲json对象转换为json字符串 -->
      dates = JSON.parse(Result),
    <!-- 得到json对象中第一个array对象 -->  date = dates[0],
    <!-- 得到array中名为glist的集合 -->  goods = date.glist;  main.style.display="block";
    <!-- 遍历该集合 -->  for(var i=0;i<goods.length;i++ ){
    <!-- 以对象.属性的方法获取数据 -->  name.innerHTML=goods[0].goodName;  goodTitle.innerHTML=goods[0].goodTitle;  goodMessage.innerHTML=goods[0].goodMessage;  goodPicture.src=goods[0].goodPicture;  goodPrice.innerHTML=goods[0].goodPrice;  goodId.innerHTML=goods[0].goodId;  }    });  };  };    </script>  </head>  <body><p>查询所有:<button id="all">点击查询</button></p><hr><div id="main" style="display:none">   <div id="goodId" ></div><p>商品名<div id="name"></div></p><p>商品概况<div id="goodTitle"></div></p><p>商品介绍<div id="goodMessage"></div></p><p>商品图片<img src="" id="goodPicture"></p><p>商品价格<div id="goodPrice"></div></p></div>  </body></html>

原创粉丝点击