12.ajax异步访问数据

在js中,处理数据固然很快,sososo就能完成所有的数据处理,我们似乎不需要使用异步传输数据

跨洋数据传输就出现了问题,一来2s过去了一回2s过去了,这对于访问者来说,这就是卡

再者 我输入了密码 提示密码错误 于是要重新输入,返回了一个网页 这时候输入的数据就会被清空,非常让人抓狂。

为了解决这个问题ajax孕育而生  

Ajax全名Asynchronous JavaScript and XML  名为异步的JavaScript和XML

Ajax使用方式非常简单

1.创建实例  xhttp = new XMLHttpRequest( )

2.发送文件 Xhttp.open("GET","地址","true/false")

3.定义在发送文件后所获取的数据

xhttp.onreadystatechange = function(){}

在完全传输完成的时候 

xhttp.readyState就会等于4 
xhttp.status就会等于200
这个时候就能在
xhttp.responseText中获取到数据
4.处理数据  
xhttp.responseText获得的数据为字符串 
要将其变为字典对象
JSON.parse(xhttp.responseText)
<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ajax调用内涵段子</title>
    <style>
        video{
            background-color: aquamarine;
        }
    </style>
    <script src="../jquery-3.6.0.js"></script>
    <script>
        $(document).ready(function () {
            xhttp = new XMLHttpRequest();
            https = "https://api.apiopen.top/getJoke?page=1&count=2&type=video";
            xhttp.onreadystatechange = function(){
                if(xhttp.readyState==4&&xhttp.status==200){
                    $("h1").html(JSON.parse(xhttp.responseText).result[0].text);
                }
                else{

                }
            }
            $("button").click(function(){
                xhttp.open("GET",https,true);
                xhttp.send();
            })
        });
    </script>
</head>
    <button>点击获取</button>
    <h1></h1>
<body>
</body>

</html>

 

posted @ 2021-08-27 17:09  轻痕微凉  阅读(100)  评论(0编辑  收藏  举报