Ajax-01-概述

什么是Ajax?

在某些项目中,我们只希望获取页面的局部数据,而不必整页刷新,Ajax解决此类需求。

Ajax原理

Ajax的原理是通过XMLhttpRequest对象向服务器发送请求
用法示例

<body>
    <div class="container">
        <h1>hello Ajax</h1>
        <button class="btn btn-info">click</button>
        <h2 id="change">这里会发生某些变化</h2>
    </div>

	<script src="/js/jquery-3.5.1.js"></script>
    <script>
        $(function(){  

            $(".btn").on('click',function(){
                var xhr = new XMLHttpRequest();//创建XHR对象
                xhr.open("get","/data");//规定请求类型和路径
                xhr.send();//发送请求
                xhr.onreadystatechange = function(){//监听readyState事件
                
                //0:请求未初始化
                // 1:服务器连接已建立
                // 2:请求已接受
                // 3:请求处理中
                // 4:请求已经完成
                
                    if(xhr.readyState === 4&& xhr.status ===200){
                            $("#change").html(xhr.responseText)
                    }
                }
          })
        })
    </script>
</body>

Ajax封装

若需求为获取后台数据,则由于 return 不适用于异步的情况,可以有以下获取异步信息的方案

回调函数法封装

// 用回调函数封装ajax方法
            function myAjax(method,url,next){
                var xhr = new XMLHttpRequest();//创建XHR对象
                xhr.open(method,url);//规定请求类型和路径
                xhr.send();//发送请求
                xhr.onreadystatechange = function(){//监听readyState事件
                
                // 0:请求未初始化
                // 1:服务器连接已建立
                // 2:请求已接受
                // 3:请求处理中
                // 4:请求已经完成
                
                    if(xhr.readyState === 4&& xhr.status ===200){
                                next(xhr.responseText)
                    }
                }
            }

使用myAjax

//通过回调函数获取
                myAjax("get","/data",function(res) { 
                    $("#change").html(res);
                })

Promise对象封装

过多的回调将让程序变得难以维护,推荐用Promise对象重新封装

			 function myAjax(method,url){
                return new Promise(function(resolve){
                    var xhr = new XMLHttpRequest();//创建XHR对象
                    xhr.open(method,url);//规定请求类型和路径
                    xhr.send();//发送请求
                    xhr.onreadystatechange = function(){//监听readyState事件
                        if(xhr.readyState === 4 && xhr.status ===200){
                            resolve(xhr.responseText)//通过resolve传出来
                        }
                    } 
                })

                
            }

使用myAjax

				myAjax("get","/data").then( res=>{
                    $("#change").html(res);
                })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值