利用AJAX后台查询数据库返回json,前台生成表格

来源:互联网 发布:网络销售模式有哪些 编辑:程序博客网 时间:2024/06/06 00:55

后台代码

public class DetailAjaxAction extends FrameAjaxCrassAction {    @Override    protected String doExecute(DataManager dm, PrintWriter out, HttpServletRequest request, SecurityForm form)            throws Exception {        String sid = request.getParameter("sid");        String sql="select * from v_user_tables where nm_sid='"+sid+"'";         DataObject dbo_result=dm.findByPrimaryKey(sql,null);        String tableName=dbo_result.getString("TABLE_NAME");        String sql1="select column_name from user_tab_columns where table_name='"+tableName+"'";         String sql2="select * from  "+tableName;        Collection colResult = dm.find(sql1, null);        Collection colResult2 = dm.find(sql2, null);        JSONArray jsa = new JSONArray();        JSONArray jsa2 = new JSONArray();        JSONObject jo2 = new JSONObject();        try {            jsa = JSONUtil.converToJsa(colResult);            jsa2 = JSONUtil.converToJsa(colResult2);            jo2.element("head",jsa);            jo2.element("data",jsa2);        } catch (Exception e) {            // TODO: handle exception        }        out.write(jo2.toString());        return null;    }}

前台

<body style="overflow: auto; width: 100%;" >    <div>        <html:form action="<%=url %>" styleId="dbaForm">            <table id="xccs" class="tableContentStyle" width="98%" border=1                cellpadding="5" cellspacing="0" align=center>                <thead>                <tr id="table"></tr>                <tbody id="table2"></tbody>                 </table>        </html:form>    </div>    <script type="text/javascript">    $(function() {            $.post("dba/table/detailAjax.do?sid=<%=sid%>",function(result){                var html='';                var result=$.parseJSON(result);                console.info(result);                var head=result.head;                var data=result.data;                $.each(head, function(i,obj) {                    html+='<th align="center"  nowrap>'+obj.COLUMN_NAME+'</th>';  //先循环表格标题                });                    $("#table").html(html);                    html='';                    $.each(data, function(j,dataobj) {                        html+='<tr>';                        $.each(head, function(i,obj) {                            var col_nm=obj.COLUMN_NAME;  //先循环列,再循环行                            html+='<td align="center" nowrap >'+dataobj[col_nm]+'</td>';   //json_key值为变量时,用中括号(dataobj[col_nm])表示                        });                    html+='</tr>'                    });                    html+=''                    $("#table2").html(html);              });    });    </script></body></html>
原创粉丝点击