首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

AJAX JSON 數據遍歷渲染:拼接 HTML vs 模板引擎 vs EasyUI DataGrid

     編輯:程式設計綜合問答

現狀代碼


success: function(data) {
    if (data.recode == 0) {
        for (var i = 0; i < data.result.list.length; i++) {
            document.getElementById("sp").innerHTML +=
                '<li class="tc-all"><span class="tc-img"><img onclick="selSPToParent(\'' +
                data.result.list[i].id + '\')" src="' + data.result.imgPath +
                data.result.list[i].imgUrl + '" width="150" height="150"/></span><span class="tc-wz">' +
                data.result.list[i].name + '</span></li>';
        }
    }
}

三種改進方案

方案一:模板字符串(ES6+,無依賴)


const tpl = (item) => `
  <li class="tc-all">
    <span class="tc-img">
      <img onclick="selSPToParent('${item.id}')" src="${data.result.imgPath}${item.imgUrl}" width="150" height="150"/>
    </span>
    <span class="tc-wz">${item.name}</span>
  </li>
`;
success: function(data) {
    if (data.recode === 0) {
        const html = data.result.list.map(tpl).join('');
        document.getElementById("sp").innerHTML = html; // 一次性賦值,避免重排
    }
}

方案二:輕量模板引擎

  • ArtTemplate / doT.js / Handlebars:預編譯模板,邏輯與視圖分離。
  • 示例:
    ``
    `template('tpl', data.result)`

方案三:EasyUI DataGrid(零手寫 HTML)


<table id="dg" title="商品列表" class="easyui-datagrid"
    data-options="url:'Reader.aspx/GetStr',method:'post',pagination:true,fitColumns:true,singleSelect:true">
    <thead>
        <tr>
            <th data-options="field:'imgUrl',formatter:imgFmt,width:100">圖片</th>
            <th data-options="field:'name',width:200">名稱</th>
        </tr>
    </thead>
</table>

function imgFmt(val, row) {
    return '<img src="' + row.imgPath + val + '" width="50" height="50"/>';
}

後端返回標準格式:{total:100, rows:[{id:1, name:'A', imgUrl:'a.jpg'},...]}

選型建議

場景推薦理由
簡單列表、項目少模板字符串零依賴、性能好、易維護
複雜邏輯、多頁復用ArtTemplate/Handlebars模板預編譯、支持條件/循環/助手函數
需要分頁/排序/編輯/導出EasyUI DataGrid開箱即用豐富交互,後端只需返回標準 JSON
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved