Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the encapsulation of Ajax based on Promise

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

本篇内容主要讲解"基于Promise如何实现对Ajax的封装",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"基于Promise如何实现对Ajax的封装"吧!

需求如下:原生ajax写起来太麻烦了,我们想用下面的写法发送ajax,如何做呢?一起来看看!

/**

* 发送get请求

* 参数是一个对象

* 对象中url是请求路径 必传项

* 对象中method是请求方式 get和post 可不传默认get

* 对象中data是请求携带的数据 必传项,且必须是对象

* 对象中headers是请求形式 formdata或json post请求可不传默认formdata

**/

sealAjax({

url: '/login',

methed: 'post',

data: {username: 'xxx', password: 111111},

headers: 'json',

}).then(data => {

console.log('成功', data)

}).catch(err => {

console.log("失败", err)

})

很简单,基于promise简单封装一下即可

function sealAjax(obj){

// 首先将传入的数据接过来

let data = obj.data

let url = obj.url

let methed = obj.methed || 'get' // 不传默认发送get请求

let headers = obj.headers || 'formdata' // 默认以表单形式发送

// 定义query变量存储query字符串,主要用于get请求

let query = ''

if (data) {

for (var i in data) {

query += i + '=' + data[i] + '&'

}

query = query.slice(0, -1) // query结果 username=xxx&password=111111

}

// 下面就是元生ajax写法

let xhr = null;

// 使用能力检测

if (window.XMLHttpRequest) {

xhr = new XMLHttpRequest()

} else if (window.ActiveXObject) {

xhr = new ActiveXObject('Microsoft.XMLHttp')

} else {

throw new Error('您的浏览器不支持ajax, 请升级')

}

// 最后返回一个promise对象

return new Promise((resolve, reject) => {

// 调用open, 用了个三元表达,如果methed是post请求就用url,否则用url和query字符串拼接

xhr.open(methed, methed === 'post' ? url : url + '?' + query, true)

// 监听事件

xhr.{

// 判断xhr的状态码

if (xhr.readyState === 4 ) {

if (xhr.status === 200) {

// 成功时 接收返回的内容

resolve(xhr.responseText)

} else {

// 失败时 接收返回的内容

reject(xhr.responseText)

}

}

}

// 设置响应头模拟为表单数据,如果传进来的是json,请求头类型就设置json,发送json字符串

// 如果传进来的是formdata,请求头类型就设置formdata,发送query字符串

if (headers.toLowerCase() === 'json') {

xhr.setRequestHeader('content-type', 'application/json;charset=utf-8')

xhr.send(JSON.stringify(data))

} else if (headers.toLowerCase() === 'formdata') {

xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded;charset=utf-8')

xhr.send(query)

}

})

}

到此,相信大家对"基于Promise如何实现对Ajax的封装"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report