js-hand-16
发表于|更新于|Js手写题
16. 手写原生AJAX
步骤
- 创建 XMLHttpRequest 实例
- 发出 HTTP 请求
- 服务器返回 XML 格式的字符串
- JS 解析 XML,并更新局部页面
了解了属性和方法之后,根据 AJAX 的步骤,手写最简单的 GET 请求。
- version 1.0:
查看答案
myButton.addEventListener('click', function () { |
- promise版本实现查看答案
function ajax(url) {
const p = new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest()
xhr.open('get', url)
xhr.onreadystatechange = () => {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status <= 300) {
resolve(JSON.parse(xhr.responseText))
} else {
reject('请求出错')
}
}
}
xhr.send() //发送hppt请求
})
return p
}
let url = '/data.json'
ajax(url).then(res => console.log(res))
.catch(reason => console.log(reason))
/img/banner/banner_2.jpeg
相关推荐
评论
公告
总结整理前端知识点 \( ̄︶ ̄*\))
持续更新中...
ヾ(•ω•`)o
持续更新中...
ヾ(•ω•`)o