标签:lang get The options app url ade ase OLE
function myAjax(options) {
let { url, type, data, onsuccess } = options
if (type.toLowerCase() === ‘get‘ && data) {
//data 传进来的需要序列化,这里默认已经序列化
//...
url = url + ‘?‘ + data
}
var xhr = new XMLHttpRequest()
xhr.open(type, url)
//这里只是模拟了成功以后的函数,需要的话还可以模拟错误等...
xhr.onload = function () {
onsuccess(xhr.responseText)
}
if (type.toLowerCase() === ‘post‘) {
xhr.setRequestHeader(‘content-type‘, ‘application/x-www-form-urlencoded‘)
xhr.send(data)
} else {
xhr.send()
}
}
//get调用
myAjax({
url: ‘./index.json‘,
type: ‘get‘,
data: ‘name=zs‘,
onsuccess: function (res) {
console.log(res);
}
})
//post调用,这里只是模拟一下,没有写接口,http报405错
myAjax({
url: ‘./index.json‘,
type: ‘post‘,
data: JSON.stringify({ name: 1 }),
onsuccess: function (res) {
console.log(res);
}
})
//index.json中只是随便写了个json对象
{
"name":"zs"
}
标签:lang get The options app url ade ase OLE
原文地址:https://www.cnblogs.com/xixiaoxi/p/13226511.html