1. 程式人生 > >Ajax傳遞List對象到前臺展示問題遇到的坑

Ajax傳遞List對象到前臺展示問題遇到的坑

post nat 展示 topic 前端jquery 原創 ply 需要 exc

後臺Json轉換

後臺傳遞的List對象,如果對象是實體類,實體類和另一個表關聯,就可能會出現以下錯誤
  org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: forum.po.Topic.replyList, could not initialize proxy - no Session

所以最好新建一個VO 視圖類,將需要展示的字段單獨拿出來(可以寫到VO類的構造方法裏去),再轉換成json串。
如果使用fastjson的話,轉換語句為:JSON.toJSONString(topicList)

前端jquery循環遍歷

前端獲取的json數據格式為 [{"":"","":""},{"":"","":""}]

在循環遍歷以前,需要先JSON.parse() 解析json字符串,再用$.each遍歷。

var topicList =JSON.parse(result.body);
$.each(topicList, function(i,topic) {
    console.log(topic);
    console.log(topic.title);
});

寫到頁面中

最後還要將數據寫到頁面上,註意jquery的語法

var target_ul = $("#topic_value_ul");
var res = []; var topicList =JSON.parse(result.body); $.each(topicList, function(i,topic) { res.push(‘<li style="text-align: left;">‘); res.push(‘<strong><span style="color: #2d64b3;font-size:16px;">‘ + topic.title + ‘</span></strong>‘); res.push(‘</li>‘); }); target_ul.empty().html(res.join(
""));

原創文章,歡迎轉載,轉載請註明出處

Ajax傳遞List對象到前臺展示問題遇到的坑