异步请求ajax

var ajax = {
	"request":function(apiType, param, callBackFunction) {
		// {"project":"http://test.m.XXX.com/"} 这个json是请求的域名
		$.getJSON("{"project":"http://test.m.XXX.com/"}", function(env){
			$(".loading").show();
		    var reqUrl = {"project":"http://test.m.XXX.com/"}+apiType+"/api.go?";
			
			// 公共参数
			var comParam = {
	    		deviceTypeOrig : 5,
	    		device_type : 5,
	    		platformSource : "app_h5"
	    	};
	    	
			var paramStr = ajax.param2str(comParam) + ajax.param2str(param);
		    console.log(reqUrl+paramStr.substr(1));
		    
		    $.ajax({
		        type: "post",
		        dataType:'json',
		        async : true,
		        contentType: "application/json;charset=utf-8", //乱码解决,
		        url: reqUrl+paramStr.substr(1),
		        data:{},
		        success: function(data, textStatus) {
		            //console.log(data);
		            //console.log(textStatus);
		            $(".loading").hide();
		            if (data && data.status.code == 0) {
		                callBackFunction(data);
		            }else{
		            	console.log("请求出错!状态值:"+ data.status.code);
		            }
		            
		        },
		        error: function(XMLHttpRequest, textStatus, errorThrown) {
		        	$(".loading").hide();
		            //console.log(XMLHttpRequest);
		            //console.log(textStatus);
		            //console.log(errorThrown);
		        }
		    });
		
		    var timer = window.setTimeout(function() {
		        requestTimeout();
		    }, 10000);
		
		    function requestTimeout() {
		        //console.log("超过一定时间隐藏loading");
		        $(".loading").hide();
		        clearTimeout(timer);
		    }
		});
	    
	},
	/**
	 * 参数拼接
	 */
	"param2str":function(obj){
		var str = "";
		for(var i in obj){
			str = str + "&" + i + "="+ obj[i];
		}
		return str;
	}
};

猜你喜欢

转载自blog.csdn.net/zhang_pengcheng/article/details/79237728