$.ajax总是报错,在react项目中用es6封装ajax请求,组件中调用总是报错,求解?

又到了把我写的小函数拿出来用的时候了,自认为还是比较简单好用的

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值