鍍金池/ 問(wèn)答/HTML/ jQuery中Ajax函數(shù)封裝

jQuery中Ajax函數(shù)封裝

$.ajax({
    type : "post",
    url : "workbench/customer/selectAll.do",
    success : function(data){
        if(data.success){
            var html = "";
            $.each( data.customerList, function(i , n){                       
                html += '<tr>';
                html += '<td><input type="checkbox" value="'+n.id+'"/></td>';
                html += '<td><a style="text-decoration: none; cursor: pointer;" onclick="window.location.href="workbench/customer/detail.jsp">'+n.name+'</a></td>';
                html += '<td>'+n.owner+'</td>';
                html += '<td>'+n.phone+'</td>';
                html += '<td>'+n.website+'</td>';
                html += '</tr>';
            })                    
            $("#customerTbody").append(html);
        }else{
            alert("查詢用戶失敗");
        }
    }
})
可不可以把上述的代碼封裝成一個(gè)方法,想什么時(shí)候調(diào)用就什么時(shí)候調(diào)用?
回答
編輯回答
兔寶寶

封裝一個(gè)方法:
function ajaxFunc(type, url, customerTbody, eachContent){

$.ajax({
type : type,
url : url,
success : function(data){
    if(data.success){
        var html = "";
        $.each( data.customerList, function(i , n){                       
           var html = eachContent;
        })                    
        $(customerTbody).append(html);
    }else{
        alert("查詢用戶失敗");
    }
}
})

}

2017年7月31日 08:57
編輯回答
真難過(guò)

當(dāng)然可以啊,你覺(jué)得不行是出于什么考慮?

2017年6月18日 02:29
編輯回答
淡墨

把它丟到函數(shù)里面調(diào)用不就是了嘛?

function name(){
    $.ajax({
    type : "post",
    url : "workbench/customer/selectAll.do",
    success : function(data){
        if(data.success){
            var html = "";
            $.each( data.customerList, function(i , n){                       
                html += '<tr>';
                html += '<td><input type="checkbox" value="'+n.id+'"/></td>';
                html += '<td><a style="text-decoration: none; cursor: pointer;" onclick="window.location.href="workbench/customer/detail.jsp">'+n.name+'</a></td>';
                html += '<td>'+n.owner+'</td>';
                html += '<td>'+n.phone+'</td>';
                html += '<td>'+n.website+'</td>';
                html += '</tr>';
            })                    
            $("#customerTbody").append(html);
        }else{
            alert("查詢用戶失敗");
        }
    }
})    
};
name();
2017年4月24日 09:52