原生JS封装Ajax方法
/**
* [ajax description]
* @param {[json]} opt [参数设置]
* @return {[type]} [description]
option设置:
{
method: 'GET',
url: '1.txt',
responseType:'xml/json',
data: {
name1:'value1',
name2:'value2'
},
success: function (response) {
alert(response);
}
}
*/
function ajax(opt) {
// 参数初始化
opt = opt || {};
opt.method = opt.method.toUpperCase() || 'POST';
opt.url = opt.url || '';
opt.async = opt.async || true;
opt.responseType = opt.responseType || '';
opt.data = opt.data || null;
opt.success = opt.success || function() {};
// 创建httpRequest
var xmlHttp = createXHR();
// 向服务器传递的参数存放在params
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 + '&' + Math.random(), opt.async);
xmlHttp.send(null);
}
// 监听请求状态
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
if (opt.responseType == 'json') {
var responseData = JSON.parse(xmlHttp.responseText);
} else if (opt.responseType == 'xml') {
var responseData = xmlHttp.responseXML;
} else {
var responseData = xmlHttp.responseText;
}
opt.success(responseData);
}
};
// 创建request请求方法
function createXHR() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("您的浏览器不支持AJAX!");
return false;
}
}
}
return xmlHttp;
}
}