写代码之前首先需要知道 AJAX 的运行原理以及其中的一些 API,这里就推荐菜鸟或者w3c 的教程了,所以我就不复述了
如下图:
开始写代码
创建对象:
var xhttp
if (window.XMLHttpRequest) xhttp = new XMLHttpRequest() // 判断浏览器类型并且创建对象
else xhttp = new ActiveXObject()
判断网络请求类型,并发送
if (obj.method == 'get' || obj.method == 'GET') {
if (data == undefined) {
xhttp.open('GET', url, async)
xhttp.send()
}
else {
xhttp.open('GET', url + splitStr(data), async)
// 由于get方法可以在url中传递参数,因此假如有传递数据,需加在url后面,下方附上 splitStr函数
xhttp.send()
}
}
else if (method == 'post' || method == 'POST') {
if(data==undefined) throw 'method POST can not without data to send'
else {
xhttp.open('POST',url,async)
xhttp.setRuquestHeader('Content-type','application/x-www-form-urlencoded')
xhttp.send(data)
}
}
else if (method == undefined) throw 'method can not be undefined'
splitStr 函数
function splitStr(data) {
let str = ''
for (var key in data) {
let s = key + '=' + data.key + '&'
str += s
}
return str.substring(0, str.length - 1)
}
编写 onreadystatechang 函数
xhttp.onreadystatechange=function(){
if(xhttp.readyState==4){
obj.success(JSON.parse(xhttp.responseText))
}
else if(xhttp.readyState==4 && (xhttp.status!=200 || xhttp.status!=304) ){
obj.error()
}
}
拼接起来
function sendAjax(obj) {
var url = obj.url
var method = obj.method
var async = obj.async==undefined? true:obj.async
var data = obj.data
function splitStr(data) {
let str = ''
for (var key in data) {
let s = key + '=' + data.key + '&'
str += s
}
return str.substring(0, str.length - 1)
}
// initial
var xhttp
if (window.XMLHttpRequest) xhttp = new XMLHttpRequest()
else xhttp = new ActiveXObject()
// send
if (obj.method == 'get' || obj.method == 'GET') {
if (data == undefined) {
xhttp.open('GET', url, async)
xhttp.send()
}
else {
xhttp.open('GET', url + splitStr(data), async)
xhttp.send()
}
}
else if (method == 'post' || method == 'POST') {
if(data==undefined) throw 'method POST can not without data to send'
else {
xhttp.open('POST',url,async)
xhttp.setRuquestHeader('Content-type','application/x-www-form-urlencoded')
xhttp.send(data)
}
}
else if (method == undefined || method=='') throw 'method can not be empty'
// response
xhttp.onreadystatechange=function(){
if(xhttp.readyState==4){
obj.success(JSON.parse(xhttp.responseText))
}
else if(xhttp.readyState==4 && (xhttp.status!=200 || xhttp.status!=304) ){
obj.error()
}
}
}
调用格式
sendAjax({
url: 'AJAX.json',
method: 'get',
async: true,
data: {
id: 100,
username:"123456"
},
success: function (data) {
console.log(data)
},
error: function () {
console.log('error data')
}
})