jQuery解析後臺傳遞到前端的json
阿新 • • 發佈:2019-02-02
後臺傳遞給前端部分的json程式碼
import org.springframework.messaging.simp.SimpMessagingTemplate; //messagingTemplate物件的建立 @Autowired(required = false) private SimpMessagingTemplate messagingTemplate; //建立需要傳遞的物件,使用messagingTemplate傳送至前端 CallBackMessage message = new CallBackMessage(); message.setDate(LocalTime.now()); message.setTitle(liveBroadcast.getTitle()); List<PictureContent> pictures = new ArrayList<PictureContent>(); for(LiveBroadcastPicture pic : prictures){ PictureContent content = new PictureContent(); content.setPicture(pic.getImgUrl()); content.setLink(pic.getContentUrl()); pictures.add(content); } message.setPictures(pictures); messagingTemplate.convertAndSend("/topic/send/"+form.getProductLineId(), message);
前端接收到的資料(字元型)
{ "title":"直播介紹",
"date":"17:13",
"pictures":
[{"picture":"/uploadImage/ot/ji/fhoiqc1t.png","link":"http://323/adfsafwe/qe"},
{"picture":"/uploadImage/8h/d2/crgq0g4r.png","link":"http://323/adfsafwe/qe"},
{"picture":"/uploadImage/jh/lt/w7ivrukb.jpg","link":"http://323"}
]
}
解析json格式的字串
方法1
var msg = '{ "title":"直播介紹", "date":"17:13", "pictures": [{"picture":"/uploadImage/ot/ji/fhoiqc1t.png","link":"http://323/adfsafwe/qe"}, {"picture":"/uploadImage/8h/d2/crgq0g4r.png","link":"http://323/adfsafwe/qe"}, {"picture":"/uploadImage/jh/lt/w7ivrukb.jpg","link":"http://323"} ] }' ; JSON.parse(msg,function(key,value){ ergodicJson(key,value) });
方法2
//JSON.stringify( ) —— 將物件序列化為JSON字串
//JSON.parse( )用於將一個 JSON 字串轉換為物件 推薦使用JSON.parse方法
var val = JSON.parse(msg);
$.each(val, function(item) {
var jValue=val[item];//key所對應的value
ergodicJson(item,jValue)
});
方法3
//$.parseJSON() 函式用於將符合標準格式的的JSON字串轉為與之對應的JavaScript物件。
var val = $.parseJSON(msg);
for(var item in val){
var jValue=val[item];//key所對應的value
ergodicJson(item,jValue)
}
解析json物件並新增到ul後面
function ergodicJson(key,val){
var keypictures ="pictures";
if(key == "date"){
datehtml ="<tt>"+value+"</tt>";
}
if(key == "title"){
titlehtml ="<p>"+value+"<p>";
}
//遍歷json物件裡面陣列
if(keypictures == key && value.length>0){
var length = value.length;
for(var j = 0;j<length;j++) {
var info = value[j];
imghtml = imghtml+"<a href='"+info.link+"'> <img src='"+info.picture+"'/></a>";
}
}
var htmlval = "<li>"+datehtml+titlehtml+imghtml+"</p></p></li>";
$("#noLi").remove();
$("#liveBroadcastUl").append(htmlval);
}