JavaScript学习笔记——Ajax

Ajax简介

Ajax 即“Asynchronous Javascript And XML”

是指一种创建交互式、快速动态网页应用的网页开发技术,无需重新加载整个网页的情况下,能够更新部分网页的技术

通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新

Ajax异步请求数据

  1. js发送一个请求去请求数据
  2. js不等待后台返回的数据
  3. js执行后面的操作
  4. 后台返回数据后,js处理返回的数据

Ajax流程

  1. 创建Ajax对象
  2. 设置请求,发送请求的地址,发送请求的方式
  3. 发送数据
  4. 设置监听时间,监听后台是否返回数据
  5. 处理数据
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        //1.创建xhr对象
        var xhr = new XMLHttpRequest();

        //2.设置请求的方法和路径
        //“GET”表单提交的数据会拼接到请求的路径里,效率高
        //“POST”会将表单的数据放置到请求的body里,数据大,比较安全

        //POST
        // xhr.open("POST","http://127.0.0.1:51328/abc.txt");

        //GET
        xhr.open("GET","http://127.0.0.1:51328/abc.txt?username=admain&password=123456");

        //3.发送数据,可以发送也可以不发送

        //POST
        // xhr.send("username=admain&password=123456");

        //GET或者POST不发送
        xhr.send();

        //4.监听后台是否返回数据
        xhr.onreadystatechange = function(){
    
    
            if (xhr.status==200&&xhr.readyState==4) {
    
    
                console.log('成功获取数据');
                console.log(xhr);
                console.log(xhr.status);
                console.log(xhr.readyState);
                //xhr.status:状态码
                //xhr.readyState:过程状态,一共5个状态,状态为4表示完成

                //5.处理数据
                var res = xhr.response;
                var h1 = document.createElement("h1");
                h1.innerHTML = res;
                document.body.appendChild(h1); 
            }
        }

    </script>
</body>
</html>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

封装Ajax

function getAjax (httpUrl,callbackFn){
    
    
    var xhr = new XMLHttpRequest();

    xhr.open("GET",httpUrl);

    xhr.send();

    xhr.onreadystatechange = function(){
    
    
        if (xhr.status==200&&xhr.readyState==4) {
    
    
            callbackFn(xhr);
        }
    }
}

调用:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="./getAjax.js"></script>
    <script>
        function fn(xhr){
    
    
            console.log(xhr);
            var h1 = document.createElement("h1");
            h1.innerHTML = xhr.response;
            document.body.appendChild(h1);
        }
        getAjax("abc.txt",fn);
    </script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/Nozomi0609/article/details/108611435