需要jquery支持
//创建ajax类
function ajaxobj(){
this.url="";
this.data="";
this.type="post";
this.async=true;//true:同步 false:异步
this.success;//成功时执行
this.error;//失败时执行
this.complete=function(XHR,TextStatus){//完成时执行
if(XHR.statusText!="OK"){
if(typeof this.error == "function"){this.error();}
console.warn(that.url+"->"+XHR.statusText)
}
};
this.timeout=120000;//120秒超时
this.send=function(){
$.ajax(this);
}
}
function ajax(url,_post,callback,error){
var _ajax = new ajaxobj();
_ajax.url=url;
_ajax.data=_post;
_ajax.success=callback;
_ajax.error=error;
_ajax.send();
}
原生js ajax
来源http://www.cnblogs.com/a757956132/p/5603176.html
/* 封装_ajax函数
* @param {string}opt.type http连接的方式,包括POST和GET两种方式
* @param {string}opt.url 发送请求的url
* @param {boolean}opt.async 是否为异步请求,true为异步的,false为同步的
* @param {object}opt.data 发送的参数,格式为对象类型
* @param {function}opt.success ajax发送并接收成功调用的回调函数
*/
function _ajax(opt) {
opt = opt || {};
opt.method = opt.method.toUpperCase() || 'POST';
opt.url = opt.url || '';
opt.async = opt.async || true;
opt.data = opt.data || null;
opt.success = opt.success || function () {};
opt.error = opt.error|| function () {};
var xmlHttp = null;
if (XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
else {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}var params = [];
for (var key in opt.data){
params.push(key + '=' + opt.data[key]);
}
var postData = params.join('&');
if (opt.method.toUpperCase() === 'POST') {
xmlHttp.open(opt.method, opt.url, opt.async);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
xmlHttp.send(postData);
}
else if (opt.method.toUpperCase() === 'GET') {
xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
xmlHttp.send(null);
}
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
opt.success(xmlHttp.responseText);
}
if(xmlHttp.readyState == 4 && xmlHttp.status != 200){
opt.error(xmlHttp);
console.warn(`[${opt.method}]${opt.url} -> ${xmlHttp.status}-${xmlHttp.statusText}`)
}
};
}
/**
* 我喜欢的样子
*/
function ajax(url,_post,callback,error){
_ajax({
method: 'POST',
url: url,
data: _post,
success: function (response) {
callback(response);
},
error: error
});
}