ajax请求的GET与POST方法封装

ajax请求封装

什么是ajax

ajax是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。

  • AJAX = 异步 JavaScript 和 XML。
  • AJAX 是一种用于创建快速动态网页的技术。
  • 通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
  • 传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。

本篇文章将ajax进行了一个简单易用的方法封装,可以直接调用

这个ajax方法适用于GET以及POST方法的请求

function ajax({url , type , data}) {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest()
        xhr.open(type, url, true)
        if (type === "POST") {
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.send(JSON.stringify(data))
        }
        else{
            xhr.send(null)
        }
        xhr.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    resolve(this.responseText)
                } else {
                    let res = { code: this.status, response: this.response }
                    reject(res)
                }
            }
        }
    })
}

下边代码是ajax方法的使用详情

//使用案例
let result = ajax({
	url: "http://www.baidu.com/",
	type:"POST",
	data:{
		username : "hello",
		password : "word"
	}
})

下边是GET与POST请求的单个封装

GET请求
function get(url){
    return new Promise( (resolve , reject) => {
        let xhr = new XMLHttpRequest()
        xhr.open('GET', url, true)
        xhr.send(null)
        xhr.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    resolve(this.responseText)
                } else {
                    let res = { code: this.status, response: this.response }
                    reject(res)
                }
            }
        }
    })
}
POST请求
function post({url , data}){
    return new Promise( (resolve, reject) => {
        let xhr = new XMLHttpRequest()
        xhr.open("POST", url, true)
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send(JSON.stringify(data))
        xhr.onreadystatechange = function () {
            if (this.readyState === 4) {
                if (this.status === 200) {
                    resolve(this.responseText)
                } else {
                    let res = { code: this.status, response: this.response }
                    reject(res)
                }
            }
        }
    })
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr.温m_

如果喜欢可以支持打赏小哥!!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值