其实json就是对象。源生的js代码并没有类的概念。对象救就是object。对象有自己的属性,也可以有自己的方法。json是一种轻量级的存储和交换信息的语言。他有自己的格式。
较为简单的json。里面只有简单的对象,key+value的形式:
var CellInfo = {
"CellId": document.getElementById("CellId").value,
"UEAmount": document.getElementById("UE value").innerText,
"BearAddDel": document.getElementById("bearvalue").innerText,
"UEAttachDe": document.getElementById("attachvalue").innerText,
"TotalDLTP": document.getElementById("dlvalue").innerText,
"TotalULTP": document.getElementById("ulvalue").innerText,
};
每个元素之间用逗号隔开。调用每个key的值可用语句。例如:CellInfo.UEAmunt,就可取出其中的值。
较为复杂的json。里面包含了对象。
var UEGroup1 = {
"UEAmount": ua[1],
"DBR1": {
"DLPackageSize": DS[1],
"ULPackageSize": US[1],
"DLTP": DP[1],
"ULTP": UP[1],
"QCI": QCI[0]
},
"DBR2": {
"DLPackageSize": DS[2],
"ULPackageSize": US[2],
"DLTP": DP[2],
"ULTP": UP[2],
"QCI": QCI[1]
},
"DBR3": {
"DLPackageSize": DS[3],
"ULPackageSize": US[3],
"DLTP": DP[3],
"ULTP": UP[3],
"QCI": QCI[2]
}
};
例如这个UEGroup1,里面的元素不仅有简单的key+value,还包含了三个对象。对象里的元素用{}括起来,彼此之间用逗号隔开。想具体访问某个元素的值也是通过逐层key,例如:UEGrooup1.DBR1.DLPackageSize
动态的往json只增加元素,增加对象。
前面说的几个都是静态的,提前写好的。那如果临时想加一个元素,例如在Cellinfo这个json中相加一个number的元素:
CellInfo.number=10;
对于往json中添加对象。例如我们想把Cellinfo和UEGroup1这两个object作为两个元素加入到另外一个大的json中:
var PETInfo = {};//声明了一个空的对象
var CellInfo = {
"CellId": document.getElementById("CellId").value,
"UEAmount": document.getElementById("UE value").innerText,
"BearAddDel": document.getElementById("bearvalue").innerText,
"UEAttachDe": document.getElementById("attachvalue").innerText,
"TotalDLTP": document.getElementById("dlvalue").innerText,
"TotalULTP": document.getElementById("ulvalue").innerText,
};
str_CellInfo = JSON.stringify(CellInfo);//将CellInfo转为字符串对象
PETInfo.CellInfo=str_CellInfo;//在PETInfo中添加名为Cellinfo的属性,并赋值
json写好后,发送给后台。至于后台怎么处理数据我们不关心。发送json的函数如下:
function post(path, params, method) {
method = method || "post";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
参数分别是后台的地址,变量,方法。变量就是我们自己写好的json,方法默认为post。例如我们想发刚刚的PETInfo
$.post('http://10.140.160.64:3012/users/ueinfo', PETInfo);
数据的发送、并获取结果的实例:
需求描述:用户填写一系列的输入框,前端获取数据,封装成json并发送给服务器,服务器会返回一个返回值,表示状态。前端需要展示这个内容提示客户。
function sendBook(){
var Book={
"openstackIP":document.getElementById("openstackIP").value,
"RAPName":document.getElementById("RAPName").value,
"RAPVer":document.getElementById("ver").value,
"OAMIP":document.getElementById("OAMIP").value
};//json封装用户输入的数据
$.post('http://10.140.160.64:3012/servers/env/book', Book)//调用post传输数据
.done((resp) => {//传输后获取服务器的返回值
alert(resp);//展示返回值
// window.location.href = 'Environment-List.html';//选择性界面跳转
});
}
存储数据有很多方法。这里我用的是localStorage。localStorage与cookie的区别如下:
① cookie在浏览器与服务器之间来回传递。
sessionStorage和localStorage不会把数据发给服务器,仅在本地保存
②数据有效期不同:
cookie只在设置的cookie过期时间之前一直有效,即使窗口或浏览器关闭。
sessionStorage:仅在当前浏览器窗口关闭前有效。
localStorage 始终有效,长期保存。
③cookie数据还有路径的概念,可以限制cookie只属于某个路径下。
存储大小也不同,cookie数据不能超过4k,sessionStorage和localStorage 虽然也有存储大小的限制,但比cookie大得多,可以达到5M或更大。
④ 作用域不用
sessionStorage不在不同的浏览器窗口中共享;
localStorage在所有同源窗口中都是共享的;
cookie也是在所有同源窗口中都是共享的;
WebStorage 支持事件通知机制,可以将数据更新的通知发送给监听者。Web Storage 的 api 接口使用更方便。
用localstage存储json的实例:
str_PETInfo=JSON.stringify(PETInfo);//将json转为字符串对象
window.localStorage.setItem("PET",str_PETInfo);//存入本地,该json的key为PET
将json取出来:
var PET=JSON.parse(window.localStorage.getItem("PET"));//将字符串转化为json
var CellInfo=JSON.parse(PET.CellInfo);//json中的Cellinfo对象转化为json
例子描述:网上订餐系统。在后台数据库分为商家表、骑手表、订单表、顾客表。那现在呢是要绘制地图,需要三者的全部信息。后台将信息发送,前台如何接受多个json并打包成易于使用的完整Json
后台代码:
@WebServlet(name="/CustomerWaiting",urlPatterns= {"/WEB-UI/pages/CustomerWaiting"})
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
response.setContentType("text/xml;character=utf-8");
//获取当前正在使用系统的用户id
CacheService cache=new CacheService();
String name=cache.Getname();
//根据用户id从数据库中取出状态为等待的订单
String hql="FROM Food food WHERE food.state like '%waiting%' AND name=?";
HibernateService hs=new HibernateService();
RiderService rs = new RiderService();
List list =hs.FoodSearch(hql, name);
List riderslist = new ArrayList();
List ownerlist = new ArrayList();
for(int i = 0; i < list.size(); i++) {
Food food = list.get(i);
String shopname = food.getShopname();
//根据订单中的骑手名属性,取出对应的负责配送的骑手的全部信息
Rider rider = rs.SearchByRiderName(food.getRidername());
//根据订单中商店名的属性,取出对应的商家的全部信息
Owner owner = rs.SearchOwnerByShopname(shopname);
riderslist.add(rider);
ownerlist.add(owner);
}
//用JSONArray将list封装成一条条的数组,装进json
JSONArray jb = JSONArray.fromObject(list);
JSONArray jb2 = JSONArray.fromObject(riderslist);
JSONArray jb3 =JSONArray.fromObject(ownerlist);
//转换成String发送给前端
response.getWriter().write(jb.toString());
response.getWriter().write(jb2.toString());
response.getWriter().write(jb3.toString());
}
后端总结:这样做的好处是,现在每个列表都有着一一对应的关系。比如在订单表里第一条,包含订单内容a、骑手001、商家002等等。那在骑手表里的第一条就是骑手001的全部信息,在商家表里的第一条就是商家002的全部信息。
前端接收:
var mapNote = {}; //制作每组数据的Json
var mapcontent2 = []; //数组形式,用来加入每一条json
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
//接收String,将三个Json分离
var json = xhttp.responseText;
// console.log(json);
for (var i = 0; i < json.length; i++) {
var ch = json.charAt(i);
if (ch == ']') {
var food = json.substring(0, i + 1);
var json2 = json.substring(i + 1);
console.log("=====food");
console.log(food);
break;
}
}
for (var j = 0; j < json2.length; j++) {
var ch2 = json2.charAt(j);
var ch3 = json2.charAt(j + 1);
if (ch2 == ']' && ch3 == '[') {
var map = json2.substring(0, j + 1);
var owner = json2.substring(j + 1);
console.log("=====riders");
console.log(map);
console.log("=====owners");
console.log(owner);
break;
}
}
//将String转换成Json
var note = JSON.parse(food);
var riders = JSON.parse(map);
var owners = JSON.parse(owner);
//填写订单信息到表格
for (var key in note) {
var table = document.getElementById("FoodWait");
var tr = table.insertRow(1);
var button = " ";
var mapbutton = "";
tr.insertCell(0).innerHTML = button;
tr.insertCell(1).innerText = note[key].id;
tr.insertCell(2).innerText = note[key].time;
tr.insertCell(3).innerText = note[key].pretime;
tr.insertCell(4).innerText = note[key].name;
tr.insertCell(5).innerText = note[key].phone;
tr.insertCell(6).innerText = note[key].place;
tr.insertCell(7).innerText = note[key].food;
tr.insertCell(8).innerText = owners[key].shopname;
tr.insertCell(9).innerHTML = mapbutton;
//绘图所需完整的JSon
var mapcon = {
"orderid": note[key].id,
"customerX": note[key].customerX,
"customerY": note[key].customerY,
"ridername": riders[key].name,
"riderphone": riders[key].phone,
"riderX": riders[key].riderX,
"riderY": riders[key].riderY,
"totalordernum": riders[key].totalordernum,
"score": riders[key].average,
"shopname": owners[key].shopname,
"shopX": owners[key].shopX,
"shopY": owners[key].shopY,
"shopphone": owners[key].phone,
"place": owners[key].place
};
//将mapcon转成str格式,并装入数组mapcontent2
var strmapcon = JSON.stringify(mapcon);
mapcontent2.push(strmapcon);
}
console.log("=====mapInfo");
console.log(mapcontent2);
addTR();
}
};
xhttp.open("GET", "CustomerWaiting", true);
xhttp.send();
因为在后台已经实现了一一对应的关系,那么在前端就可以在一个循环内,将三方的数据拼成一个较为完整的数组。那么这个数组已经无限接近当初从后台取出List封装成JsonArray的格式了,我们看下前端的conslog
根据对应关已经将零散的三方数据拼成了一个数组(mapcontent2)。那么在传参的时候也是用数组的形式,但在转换为Json的时候要额外注意:
传参调用:
button onclick="test(this,mapcontent2,'FoodWait')"
将数组转换成Json
//将数组类型转化为Json
mapNote2 = JSON.parse('['+mapcontent2+']');