關(guān)于ajax異步訪問(wèn)數(shù)據(jù)的問(wèn)題
在js中,處理數(shù)據(jù)固然很快,sososo就能完成所有的數(shù)據(jù)處理,我們似乎不需要使用異步傳輸數(shù)據(jù)
跨洋數(shù)據(jù)傳輸就出現(xiàn)了問(wèn)題,一來(lái)2s過(guò)去了一回2s過(guò)去了,這對(duì)于訪問(wèn)者來(lái)說(shuō),這就是卡
再者 我輸入了密碼 提示密碼錯(cuò)誤 于是要重新輸入,返回了一個(gè)網(wǎng)頁(yè) 這時(shí)候輸入的數(shù)據(jù)就會(huì)被清空,非常讓人抓狂。
為了解決這個(gè)問(wèn)題ajax孕育而生
Ajax全名Asynchronous JavaScript and XML 名為異步的JavaScript和XML
Ajax使用方式非常簡(jiǎn)單
1.創(chuàng)建實(shí)例 xhttp = new XMLHttpRequest( )
2.發(fā)送文件 Xhttp.open("GET","地址","true/false")
3.定義在發(fā)送文件后所獲取的數(shù)據(jù)
xhttp.onreadystatechange = function(){}
在完全傳輸完成的時(shí)候
xhttp.readyState就會(huì)等于4
xhttp.status就會(huì)等于200
這個(gè)時(shí)候就能在
xhttp.responseText中獲取到數(shù)據(jù)
4.處理數(shù)據(jù)
xhttp.responseText獲得的數(shù)據(jù)為字符串
要將其變?yōu)樽值鋵?duì)象
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){ $("h1").html(JSON.parse(xhttp.responseText).result[0].text); } else{ } } $("button").click(function(){ xhttp.open("GET",https,true); xhttp.send(); }) }); </script> </head> <button>點(diǎn)擊獲取</button> <h1></h1> <body> </body> </html>
到此這篇關(guān)于ajax異步訪問(wèn)數(shù)據(jù)的文章就介紹到這了,更多相關(guān)ajax異步訪問(wèn)數(shù)據(jù)內(nèi)容請(qǐng)搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!
