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


后台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(""));

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM