1. 程式人生 > 其它 >ajax解析json物件集合

ajax解析json物件集合

這個需求是我們做專案經常遇到的,當你想渲染表格的資料,你的資料在servlet中存在了arraylist中,你想把arraylist傳到ajax的data中,這時候就需要用到ObjectMapper物件來傳遞json資料,在ajax中用tableVue進行解析。

 

Servlet

 String LinesName = request.getParameter("LinesName");
            mannger dao = new mannger();
            ArrayList<Lines> linesarray = new ArrayList<Lines>();
            dao.SelectLines(linesarray,LinesName);
            response.setContentType(
"text/html;charset=UTF-8"); // ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(response.getWriter(),linesarray);//傳遞arraylist物件

html

  <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
            <legend>Information</legend
> </fieldset> <div class="layui-form" id="Ai"> <table class="layui-table" id="information"> <colgroup> <col width="auto"> <col width="auto"> <col width="auto"
> <col width="auto"> <col width="auto"> <col width="auto"> <col width="auto"> <col width="auto"> </colgroup> <thead> <tr > <th>線路ID</th> <th>線路名稱</th> <th>車站ID</th> <th>車站名稱</th> </tr> </thead> <tbody> <tr v-for="site in itemss"> <td> {{ site.linesID }}</td> <td> {{ site.linesName }}</td> <td> {{ site.siteID }}</td> <td> {{ site.siteName}}</td> </tr> </tbody> </table> </div> <script> function Information(){ var LinesName = $("#LinesName").val(); var tableVue = new Vue({ el:"#information", data:{ itemss:[] } }); $.ajax({ url: "Select?method1=SelectLines", type: "GET", data: {"LinesName":LinesName}, success: function (data) { //var data = JSON.parse( jsonObj );//解析json物件 console.log(data); tableVue.itemss=data; },//響應成功後的回撥函式 error: function () { alert("出錯啦...") },//表示如果請求響應出現錯誤,會執行的回撥函式 dataType: "json"//設定接受到的響應資料的格式 }); document.getElementById("Bi").style.display="none"; document.getElementById("Ai").style.display="block"; document.getElementById("Ci").style.display="none"; } </script>

在表格中

  <tr v-for="site in itemss">
                    <td> {{ site.linesID }}</td>
                    <td> {{ site.linesName }}</td>
                    <td> {{ site.siteID }}</td>
                    <td> {{ site.siteName}}</td>

                </tr>
具體的名稱要在網頁控制檯來檢視,一般第一個字母是小寫的。

實現效果

 

 

這個功能需要匯入很多jar包,因為各種原因,我就不在上傳,需要的可以聯絡我,有什麼問題也可以私信我,歡迎來訪!!!