您好,登錄后才能下訂單哦!
這篇文章主要介紹如何實現(xiàn)ajax異步訪問數(shù)據(jù),文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
在js中,處理數(shù)據(jù)固然很快,sososo就能完成所有的數(shù)據(jù)處理,我們似乎不需要使用異步傳輸數(shù)據(jù)
跨洋數(shù)據(jù)傳輸就出現(xiàn)了問題,一來2s過去了一回2s過去了,這對于訪問者來說,這就是卡
再者 我輸入了密碼 提示密碼錯誤 于是要重新輸入,返回了一個網(wǎng)頁 這時候輸入的數(shù)據(jù)就會被清空,非常讓人抓狂。
為了解決這個問題ajax孕育而生
Ajax全名Asynchronous JavaScript and XML 名為異步的JavaScript和XML
Ajax使用方式非常簡單
1.創(chuàng)建實例 xhttp = new XMLHttpRequest( )
2.發(fā)送文件 Xhttp.open("GET","地址","true/false")
3.定義在發(fā)送文件后所獲取的數(shù)據(jù)
xhttp.onreadystatechange = function(){}
在完全傳輸完成的時候
xhttp.readyState就會等于4
xhttp.status就會等于200
這個時候就能在
xhttp.responseText中獲取到數(shù)據(jù)
4.處理數(shù)據(jù)
xhttp.responseText獲得的數(shù)據(jù)為字符串
要將其變?yōu)樽值鋵ο?br/>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調(diào)用內(nèi)涵段子</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){ $("h2").html(JSON.parse(xhttp.responseText).result[0].text); } else{ } } $("button").click(function(){ xhttp.open("GET",https,true); xhttp.send(); }) }); </script> </head> <button>點擊獲取</button> <h2></h2> <body> </body> </html>
以上是“如何實現(xiàn)ajax異步訪問數(shù)據(jù)”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。