验证中...
助力高校计算机教育 —— 码云为老师推出免费高校版,高达 200 人的协作团队
Languages: JavaScript
Categories: JavaScript 工具
Latest update 2018-06-14 19:52
发送 GET 或 POST Ajax请求的 Promise 代码片段
Raw Copy
/**
* @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))
})
}

Comment list( 0 )

You need to Sign in for post a comment

10_float_left_people 10_float_left_close