JS 中 ajax 的原理是什么?如何封装一个 ajax 请求?

原理:通过 XMLHttpRequest 对象来向服务器发送异步请求,从服务器获取数据,然后用 JS 来操作 DOM 去更新页面

实现过程

1. 创建 Ajax 的核心对象 XMLHttpRequest 对象

  • new XMLHttpRequest() 实例化对象

2. 通过 XMLHttpRequest 对象的 open() 方法与服务端建立连接

  • new XMLHttpRequest().open(method:表示请求方式,url:服务器的地址)

3. 构建请求所需的数据内容,并通过 XMLHttpRequest 对象的 send() 方法发送给服务器端

  • new XMLHttpRequest().send(body:发送的数据) 
  • 如果使用 get 请求发送数据,那么 send() 参数设置为 null (即send(null))

4. 通过 XMLHttpRequest 对象提供 onreadystatechange 事件监听服务器端的通信状态

  • new XMLHttpRequest().onreadystatechange 主要监听的属性是 实例化对象中 readyState(五个状态) 
  • 0:open未调用,1:send 未调用;2:send 已调用,响应头和响应状态已经返回;3:响应体正在下载,responseText(接收服务端相应的结果) 获取都部分数据;4:整个请求过程以已经完毕
  • 只要 readyState 属性值发生了改变,onreadyStatechange 被触发

5. 接受并处理服务端向客户端相应的数据结果

6. 将处理结果更新到 HTML 页面中

const xhr = new XMLHttpRequest()
xhr.open("GET",url)	// url 指的是服务器地址
xhr.send(null)
xhr.onreadystatechange = function() {
    if(xhr.readyState === 4){
        if(xhr.status >= 200 && xhr.status < 300){
            // console.log(xhr.responseText)
            let obj = JSON.parse(xhr.responseText)
            console.log(obj)
            obj.result.forEach(item =>{
                var div = document.creatElement('div')
                div.innerHTML = item.name
                document.querySelector('body').appendChild(div)
            })
        } else if(chr.readyState >= 400){
            console.log("错误信息" + xhr.status)
        }
    }
}

JS 中如何封装一个 ajax 请求?

请求方式,请求地址,请求参数,请求参数的类型

请求返回结果

function ajax(options) {
	// 创建 XMLHttpRequest 对象
    const xhr = new XMLHttpRequest()
    // 初始化参数内容
    options = options || {}
    options.type = (options.type || 'GET').toUpperCase()
    options.dataType = options.dataType || 'json'
    const params = options.data
    // 发送请求
    if(options.type === 'GET'){
        // 第三个参数 async:b布尔值,表示是否异步执行操作
        xhr.open('GET', options.url + "?" + params,true)
        xhr.send(null)
    } else if(options.type === 'POST') {
        xhr.open('POST',options.url,true)
        xhr.send(params)
    }
    // 接收请求
    xhr.onreadystatechange = function() {
        if(xhr.readyState === 4) {
            if(xhr.status >= 200 && xhr.status < 300) {
                // responseText 字符串形式的响应数据
                // responseXML XML 形式的响应数据
                options.success(xhr, responseText, responseXML)
            } else {
                options.fail(`参数错误` + status)
            }
        }
    }
}
ajax({
    type:'get',
    dataType: 'json',
    data: {
        limit:10
    },
    url: '',
    success: function(text,xml){	// 请求成功之后的回调函数
        console.log(JSON.parse(text))
    },
    fail: function(status) {		//请求失败之后的回调函数
        console.log(status)
    }
})
function getParams(data) {
    let arr = []
    for(let key in data) {
        arr.push(`${key}=${data[key]}`)
    }console.log(arr)
}
getParams()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

只想搞钱的饼干

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值