layui 中封裝ajax table


由於項目寫了一大半需要添加的全局性的東西太多,故封裝了這種修改比較小的方式。

 

 

 

commonRequest.js

layui.define(['jquery','table'], function(exports){
    var $ = layui.jquery,table=layui.table;
    var obj = {
        ajax: function (obj) {
            if (!obj.headers) {
                obj.headers = {
            // 兼容IE9 'cache-control': 'no-cache', 'Pragma': 'no-cache', 'Authorization': window.sessionStorage.getItem("token") }; } if (!obj.type) obj.type = "GET"; if (!obj.dataType) obj.dataType = "json"; // 配置為false時,表示不從瀏覽器緩存中獲取數據,調試時可以看到,發Get請求時,會自動加上時間戳 if (!obj.cache) obj.cache = false; if (!obj.async) obj.async = true; obj.crossDomain = true === !(document.all);//這句是關鍵 if (!obj.error) { obj.error = function (err) { layer.msg("網絡連接失敗!"); console.log(err); } } console.log(obj); $.ajax(obj); }, render: function (obj) { obj.headers = { 'cache-control': 'no-cache', 'Pragma': 'no-cache', 'Authorization': window.sessionStorage.getItem("token") }; console.log(obj); table.render(obj); } }; //輸出接口 exports('commonRequest', obj); // 使用的模塊名稱 });

 配置configRequest.js

注意:一個html中layui.config只能有一個

layui.config({
    base: '../../../../common/'      //自定義layui組件的目錄 
}).extend({ //設定組件別名
    common:   'commonRequest',
});

引入

<script src="../../../../common/commonTbRqs.js"></script> // 如果有別的模塊配置在下面使用頁面,這種方法會報錯

  

使用

layui.use(['table','commonRequest'],function(){
 var table=layui.table, commonRequest=layui.commonRequest;
// 表格渲染
    commonRequest.render({
            elem: tableConfig.elem, //指定原始表格元素選擇器(推薦id選擇器)
            height: tableConfig.height, //容器高度
            cols: tableConfig.cols, //設置表頭
            url: tableConfig.params ? tableConfig.getUrl() : url,
            page: tableConfig.page != false ? true : false,
            where: requestParam,
            headers: {'Authorization':  window.sessionStorage.getItem("token")}
        })
// ajax請求
   commonRequest.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: "json",
        success: function(data) {
       
        }
      });

})

  

 

 

 

 


免責聲明!

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



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