原生ajax发送get、post请求

ajax.js

const ajax = {}

ajax.request = function (url,data,method = 'POST') {
  return new Promise((resolve, reject) => {
    const xmlHttp = new XMLHttpRequest()
    xmlHttp.open(method,method === 'POST' ? url : `${url}?data=${JSON.stringify(data)}`)  // get方法加多了一个data字段
    xmlHttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')   // 设置json请求头
    xmlHttp.send(method === 'POST' ? JSON.stringify(data) : null)
    xmlHttp.onreadystatechange = function () {
      if(xmlHttp.readyState === 4) {
        if(xmlHttp.status === 200) {
          console.log(JSON.parse(xmlHttp.responseText))
          resolve(JSON.parse(xmlHttp.responseText))
        }
        if(xmlHttp.status === 404) {
          reject(xmlHttp.responseText)
        }
      }
    }
  })
}

export default ajax

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="module">
    import ajax from './ajax.js'
    ajax.request('http://127.0.0.1:3000/test',{
      x: [1,2],
      y: 2
    },'GET').then(res => {
        console.log(res)
    })
    ajax.request('http://127.0.0.1:3000/test',{
        x: [1,2],
        y: 2
    },'POST').then(res => {
        console.log(res)
    })
</script>
</body>
</html>

app.js

原生ajax会有跨域问题,后台要允许跨域访问,这里是express框架

// 允许跨域
app.all('*', function (req, res, next) {
    console.log('收到了请求')
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type')
    res.header('Access-Control-Allow-Methods', '*')
    res.header('Content-Type', 'application/json;charset=utf-8')
    next()
})

app.post('/test',function (req,res,next) {
    console.log(req.body)
    res.json({
        a: 1,
        b: 2
    })
})

app.get('/test',function (req,res,next) {
    console.log(req.query)
    res.json({
        a: 1,
        b: 2
    })
})

以上就是原生ajax的简单运用,在一些轻量级的应用上可以自己封装一个小的ajax函数,而不用引入第三方的包,从而使代码的体积更小化

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值