验证中...
开源中国 2018 年度最后一场技术盛会邀你来约~错过就要等明年啦!点此立即预约
语言: JavaScript
分类: JavaScript 工具
最后更新于 2018-12-09 10:12
发送 GET 或 POST Ajax请求的 Promise 代码片段
原始数据 复制代码
/**
* @description The method will send a Ajax request with Promise.
* @param {String} url
* @returns {Promise}
*/
function get(url) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest()
req.open('GET', url)
req.onload = () => {
if (req.status === 200) {
resolve(req.response)
} else {
reject(Error(req.response))
}
}
req.onerror = _ => reject(Error(req.response))
req.send()
})
}
/**
* @description The method will send a Ajax request with Promise.
* @param {String} url
* @param {Object} data
* @returns {Promise}
*/
function post(url, data) {
return new Promise((resolve, reject) => {
let req = new XMLHttpRequest()
req.open('POST', url)
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
req.send(data)
req.onload = () => {
if (req.status === 200) {
resolve(req.response)
} else {
reject(Error(req.response))
}
}
req.onerror = _ => reject(Error(req.response))
})
}

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助