jQuery里面ajax请求的封装

为了避免ajax漫天飞,我们需要对jQuery的代码进行封装,封装代码:

function api_request(name, params, cb, scope, async, el) {
	if (async == null)
		async = true;

	console.log('调用接口:
%s,
参数列表:', REQUEST_URL+name, params);
	$.ajax( {
		url : REQUEST_URL+name,
		async : async,
		data : params,
		type : 'POST',
		dataType:'json',
		cache : false,
		timeout:70000,
		success : function(data, textStatus) {
			//alert(data.obj[0].id);
			if (data.resultCode == 0001) {
				window.location.href = 'common/index.jsp?' + $.param( {
					to : window.location.href});
			    return;

			}

			if (data.resultCode != 0000 && data.resultCode != 0007) {
			}
			cb.call(scope || window, data, textStatus);
		},
		error:function(xhr){
			 alert("readyState: " + xhr.readyState + "
status: " + xhr.status);
		}
	});
};

请求方式:

api_request('../../' + HB_SPECIAL_NUM_DEL, param, cb, null, true, null);

  

加载数据:

//加载数据
	function cb(data, textStatus) {
		if(data.status){
			console.log(data.obj);
			data.obj = JSON.parse(data.obj);
			console.log(data.obj);
			var content = data.obj.content;
			if (content.length > 0) {
				for (var i = 0; i < content.length; i++) {
					h = "<tr>";
					/*h += '<td class="center"><label class="pos-rel"><input type="radio" class="ace" name="id" value="' + content[i].id + '"><span class="lbl"></span></label></td>';*/
					h += "<td>" + content[i].tel + "</td>";
					h += "<td>" + (content[i].areaNo && content[i].areaNo != '-1'?content[i].areaNo:'') + "</td>";
					h += "<td>" + (content[i].rangeType==1?'区域':'业务') + "</td>";
					h += "<td>" + content[i].productId + "</td>";
					h += "<td>" + (content[i].createTime?common.longTimeFormat(content[i].createTime):'') + "</td>";
					h += "<td>" + (content[i].source?getSource(content[i].source):'') + "</td>";
					h += "<td>" + getMemo(content[i].memo) + "</td>";
					h += "<td>" + (content[i].nodeCode?content[i].nodeCode:'') + "</td>";
					h += "<td>" + (content[i].adminNamel?content[i].adminNamel:'') + "</td>";
					h += "<td ><div class='btn-group'>" +
					"<a href='JavaScript:void(0);' style='color:#FFFFFF;' " +
					"onclick='del(""+content[i].id+"");'>" +
					"<button class='btn btn-xs btn-danger border-radius'>" +
					"<i class='ace-icon fa fa-trash-o'>" +
					" 删除</i></button></a>" +
					"</div></td>";
					h += "</tr>";
					$html.append(h);
				}
				
				/*$("#roleListPage").pagination(data.total, {
					callback: pageselectCallback,
					prev_text: '<上一页',
					next_text: '下一页 >',
					items_per_page: size,
					num_display_entries: 6,
					current_page: page,
					num_edge_entries: 2
				});*/
			} else {
				h = "<tr class='center'><td colspan='10'>暂无数据</td></tr>";
				$html.append(h);
			}
		}else{
			h = "<tr class='center'><td colspan='10'>"+data.desc+"</td></tr>";
			$html.append(h);
		}
	}

  

原文地址:https://www.cnblogs.com/JAYIT/p/9640695.html