您的位置:首頁技術文章
文章詳情頁

關于ajax異步訪問數據的問題

瀏覽:115日期:2022-06-12 11:24:49

在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>

到此這篇關于ajax異步訪問數據的文章就介紹到這了,更多相關ajax異步訪問數據內容請搜索以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持!

標簽: Ajax
国产综合久久一区二区三区