1.Json的格式
其實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的屬性,並賦值
2.json的發送
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';//選擇性界面跳轉
});
}
3.json在本地的存儲
存儲數據有很多方法。這裏我用的是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
4.多個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<Food> list =hs.FoodSearch(hql, name);
List<Rider> riderslist = new ArrayList();
List<Owner> 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 = "<button type=\"button\" data-toggle=\"modal\" data-target=\"#myModal\" class=\"btn btn-danger btn-circle\"onclick=\"Operate(this,'t2','delete')\"><i class=\"fa fa-times\"></i></button> <button type=\"button\" data-toggle=\"modal\" data-target=\"#myModal2\" class=\"btn btn-primary btn-circle\" onclick=\"Operate(this,'t3','update')\"><i class=\"fa fa-pencil\"></i></button> ";
var mapbutton = "<button onclick=\"test(this,mapcontent2,'FoodWait')\" type=\"button\" data-toggle=\"modal\" data-target=\"#myModal3\" class=\"btn btn-primary btn-circle\"><i class=\"glyphicon glyphicon-map-marker\"></i></button>";
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+']');