var zwt = zwt || {}
zwt.ajax = function (options) {
// options = {url:'',method:'',data:'',callback:'',async:''}
// 默认参数
options.url = options.url || ''
options.method = options.method || 'get'
options.data = options.data || ''
options.callback = options.callback || ''
options.async = options.async || true
// get请求-拼接url
if (options.method.toLowerCase() == 'get') {
if (typeof options.data == 'object') {
var arr = []
for (var k in options.data) {
arr.push(k + '=' + options.data[k])
}
options.data = arr.join('&')
}
options.url += (options.url.indexOf('?' == -1) ? '?' : '') + options.data
}
// post请求-转换字符串
if (options.method.toLowerCase() == 'post') {
if (typeof options.data == 'object') {
var arrs = []
for (var k in options.data) {
arrs.push(k + '=' + options.data[k])
}
options.data = arrs.join('&')
}
}
// 创建发送请求
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP') // 兼容ie
xhr.open(options.method, options.url, options.async)
if (options.method == 'post') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send(options.data)
} else {
xhr.send(null)
}
// 异步请求
if (options.async == true) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
callcall()
}
}
}
// xhr.abort(); // 取消异步请求
// 同步请求
if (options.async == false) {
callcall()
}
// 返回状态判断
function callcall () {
if (xhr.status == 200) {
options.callback(xhr.responseText)
} else {
options.callback('error:' + xhr.status + xhr.statusText)
}
}
}
zwt.ajax({
url: HOST + '/api/v1/oauth/token',
data: {
appId: appid,
appSecret: appsecret
},
callback: function (res) {
console.log(res)
}
})