又到了把我写的小函数拿出来用的时候了,自认为还是比较简单好用的
const AjaxGet = function( method, url, callback ){
var xhr = new XMLHttpRequest()
xhr.open(method, url, true)
xhr.withCredentials = true
xhr.send()
xhr.onreadystatechange = function(){
if((xhr.readyState == XMLHttpRequest.DONE) && (xhr.status == 200)){
callback(JSON.parse(xhr.responseText))
}else{
callback({errno:false})
}
}
}
export default AjaxGet
使用的话举例,GET方式,还有delete方式都可以用这个
import AjaxGet from 'libs/ajaxGet.js'
AjaxGet('GET', '/api/user/initme', (res) => {
if (res.errno) {
this.setState({
me: res.meData
})
} else if (res.message === 'nologin') {
alert("无法获得用户信息,将回到登陆页面")
window.location = "/login"
}
})
send的话需要多传入一个发送的数据
无非就是提取出ajax时候必须的几个元素,封装掉那些对于你项目不需要的地方,不需要通过class的形式,只是一个普通的函数而已,类似于react的无状态组件,你看无状态组件其实也是一个函数。传入一个callback,ajax完成的时候会调用它。我这里res.errno本来是指望服务器传回一些错误代码的,然而后来嫌麻烦就没有定义,只是传回true和false了
AjaxSend放下面来,方便你看。 post,put都可以用ajaxSend
const AjaxSend = function( action, url, data, callback) {
var xhr = new XMLHttpRequest()
xhr.open(action, url, true)
xhr.withCredentials = true
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function(){
if ((xhr.readyState == XMLHttpRequest.DONE) && (xhr.status == 200)) {
callback(JSON.parse(xhr.responseText))
}
}
xhr.send(JSON.stringify(data))
}
export default AjaxSend