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);
                })

猜你喜欢

转载自blog.csdn.net/baidu_41656912/article/details/114297121