11.手写原生ajax

11.ajax:

        /*
    实现过程:
        1.创建Ajax的核心对象 XMLHttpRequest对象
            new XMLHttpRequest()
        2.通过实例化对象中的open()与服务器建立连接
            open(method:表示请求方式,url:服务器的地址)
        3.构建请求所需的数据内容,并通过实例化对象中的send()方法发给服务器
            send(body:发送的数据)
            如果使用get请求发送数据,send()参数设置为null
        4.通过实例化对象提供的 onreadystatechange 事件监听服务器的通信状态
            onreadystatechange 主要监听的属性是实例对象中的readyState
            readyState 五种状态:
                0:open()方法未调用,还没建立连接
                1:send()方法未调用,还没发送请求
                2:send()已调用,响应头和响应状态已返回
                3:响应体正在下载,responseText(接收服务端响应结果),获取部分数据
                4:整个请求过程已经完毕
                只要readyState属性值发生改变,onreadystatechange事件就被触发
        5.接受并处理服务端向客户端相应的数据结果
        6.将处理结果更新到HTML页面中
 */
        function ajax(url, data) {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            // post请求:
            // 1.xhr.open('POST', url, true);
            // 2.xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // responseText:以字符串的形式返回
                        // console.log(JSON.parse(xhr.responseText));
                        console.log(xhr.responseText);
                    }
                }
            }
            xhr.send(null);
            // 3.xhr.send(data);
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值