ajax简单封装
/**
* jq操作扩展
* @param $
*/
(function($){
/**
* 判断字符串是否为空
*/
$.isEmptyStr = function(str){
if(null != str && '' != str && 'undefined' != str)
return false;
return true;
};
/**
* 获取url中的参数
*/
$.getUrlParam = function(url, name) {
var theRequest = {};
if (url.indexOf("?") != -1) {
var str = url.substr(url.indexOf("?") + 1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
var key = strs[i].substr(0, strs[i].indexOf('='));
var val = strs[i].substr(strs[i].indexOf('=') + 1, strs[i].length);
theRequest[key]= val;
}
}
return theRequest[name];
};
/**
* 判断数组是否为空
*/
$.isEmptyArray = function(list){
if(list && list instanceof Array && list.length > 0)
return false;
return true;
};
/**
* 对ajax进行简单封装
* url 发送请求的地址
* params 发送到服务器的数据,数组存储,如:{"date": new Date().getTime(), "state": 1}
* async 默认值: true。默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。
* 注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
* dataType 默认 application/json;charset=utf-8,常用的如:application/json;charset=utf-8(json)、application/x-www-form-urlencoded; charset=UTF-8(form)
* contentType 默认json, 预期服务器返回的数据类型,常用的如:xml、html、json、text
* successfn 成功回调函数
* errorfn 失败回调函数
*/
$.ajaxReq = function (url, params, successfn, conentType, dataType, async, errorfn) {
dataType = (dataType == null || dataType == "" || typeof (dataType) == "undefined") ? "json" : dataType;
params = (params == null || params == "" || typeof (params) == "undefined") ? {} : params;
async = (async == null || async == "" || typeof (async) == "undefined") ? "true" : async;
contentType = (conentType == null || conentType == "" || typeof (conentType) == "undefined") ? "application/json;charset=utf-8" : "application/x-www-form-urlencoded";
$.ajax({
type : "post",
async : async,
data : params,
url : url,
timeout: 60000,
contentType: contentType,
dataType: dataType,
success : function (d) {
if($.isFunction(successfn))
successfn(d);
},
error: function (e) {
if($.isFunction(errorfn))
errorfn(e);
}
});
};
/**
* url 发送请求的地址
* params 发送到服务器的数据,数组存储,如:{"date": new Date().getTime(), "state": 1}
* return 返回json数据
*/
$.getData = function(url, params){
var retData = {};
params = (params == null || params == "" || typeof (params) == "undefined") ? {} : params;
$.ajax({
type:"post",
url:url,
dataType:"json",
data:params,
cache:false,
async:false,
timeout:60000,
success:function(data) {
retData = data;
},
error:function(err) {
retData.exception = err;
retData.msg = err.responseText || "请求失败";
}
});
return retData;
}
/**
* url 发送请求的地址
* params 发送到服务器的数据,数组存储,如:{"date": new Date().getTime(), "state": 1}
* return 返回html界面
*/
$.loadHtml = function(url, params){
var html = "";
params = (params == null || params == "" || typeof (params) == "undefined") ? {} : params;
$.ajax({
type: "get",
url: url,
dataType: "html",
data: params,
cache: false,
async: false,
timeout: 60000,
success: function(data) {
html = data;
},
error: function(err) {
html = err.responseText || "请求失败";
}
});
return html;
}
})(jQuery);