function ajax(opt) {
opt = opt || {}; // 对实参处理
var xmlhttp, method, url, async, dataType, data;
method = opt.method || 'GET'; // 默认method为GET
method = trim(method).toUpperCase(); //转换成大写并去除空格
url = opt.url //请求地址
url = trim(url);
async = opt.async || true; // 默认为异步请求
dataType = opt.dataType || 'HTML'; // 设置跨域
dataType = trim(dataType).toUpperCase();
data = opt.data || {}; // 发送参数
function trim(str) {
return str.replace(/^\s+|\s+$/g, ""); // 删除左右空格
};
var formatParams = function () { // 定义格式化参数函数
if (typeof (data) == "object") {
var str = "";
for (var key in data) {
str += key + "=" + data[pro] + "&";
}
data = str.substr(0, str.length - 1);
}
if (method == 'GET' || dataType == 'JSONP') {
if (url.lastIndexOf('?') == -1) {
url += '?' + data;
} else {
url += '&' + data;
}
}
}
if (window.XMLHttpRequest) { // 创建XMLHttpRequest对象
//Chrome || Firefox
xmlHttp = new XMLHttpRequest();
} else {
//IE
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (dataType == 'JSONP') { // 跨域请求
if (typeof (opt.beforeSend) == 'function') opt.beforeSend(xmlHttp);
var callbackName = ('jsonp_' + Math.random()).replace(".", "");
var oHeader = document.getElementsByTagName('header')[0];
data.callback = callbackName;
var ele = document.createElement('script');
ele.type = "text/javascript";
ele.onerror = function () {
console.log('failed');
opt.error && opt.error("failed");
};
oHeader.appendChild(ele);
window[callbackName] = function (json) {
oHeader.removeChild(ele);
window[callbackName] = null;
opt.success && opt.success(json);
};
formatParams();
ele.src = url;
return;
} else {
formatParams();
xmlHttp.open(method, url, async);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8"); // 设置响应头
if (typeof (opt.beforeSend) == 'function') opt.beforeSend(xmlHttp);
xmlHttp.send(data); // 发送请求
xmlHttp.onreadystatechange = function () { // 响应处理
if (xmlHttp.status != 200) {
console.log(xmlHttp.status + 'failed');
opt.error && opt.error(xmlHttp.status + 'failed');
return;
}
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
if (dataType == 'JSON') {
try {
res = JSON.parse(xmlHttp.responseText);
} catch (e) {
console.log('json格式错误');
opt.error('json格式错误');
}
} else if (dataType == 'XML') {
res = xmlHttp.responseXML;
} else {
res = xmlHttp.responseText;
}
opt.success && opt.success(res);
}
}
}
}
<center>ajax同域跨域jsonp函数封装</center>
最新推荐文章于 2024-11-17 18:47:06 发布