简单封装一个Ajax函数,方便在以后的开发中可以直接使用。代码如下:
function myAjaxAdv(obj) {
var defaults = {
type: 'get',
url: '#',
dataType: 'json',
data: {},
sync: true,
success: function(result) {}
}
for (var key in obj) {
defaults[key] = obj[key];
}
//兼容IE浏览器
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
//得到params
var parmas = "";
for (var attr in defaults.data) {
parmas += attr + "=" + defaults.data[attr] + "&";
}
if (parmas) {
parmas = parmas.substring(0, parmas.length - 1);
}
//准备发送
if (defaults.type == 'get') {
defaults.url += '?' + parmas;
}
xhr.open(defaults.type, defaults.url, defaults.sync);
//执行发送
if (defaults.type == 'get') {
xhr.send(null);
} else if (defaults.type == 'post') {
xhr.setRequestHeader('Content-type","application/x-www-form-urlencoded');
xhr.send(parmas);
}
//判断异步或同步,获取返回值
if (defaults.sync) {
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var result = null;
if (defaults.dataType == 'json') {
result = xhr.responseText;
result = JSON.parse(result);
} else if (defaults.dataType == 'xml') {
result = xhr.responseXML;
} else {
result = xhr.responseText;
}
defaults.success(result);
}
}
}
} else {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var result = null;
if (defaults.dataType == 'json') {
result = xhr.responseText;
result = JSON.parse(result);
} else if (defaults.dataType == 'xml') {
result = xhr.responseXML;
} else {
result = xhr.responseText;
}
defaults.success(result);
}
}
}
}
参数名 | 类型 | 说明 |
---|---|---|
type | String | 请求类型,默认为GET,有效值:POST |
url | String | 服务器接口请求地址 |
dataType | String | 返回值类型,默认为JSON,有效值:XML,text |
data | Object | 请求的参数值,采用键值对形式。data:{ key: value } |
success | Function | 接口调用成功的回调函数 |
sync | Boolean | 异步或同步请求。true为异步,false为同步。默认为true。 |
示例代码:
myAjaxAdv({
url:'https://www.example.com',//仅为示例,并非真实地址
type:'get',
data:{
key:value
},
success:function(result){
console.log(result);
}
})