ajax 第三節 get引數傳遞 post請求體設定
阿新 • • 發佈:2021-11-04
======================== get引數傳遞 ==========================
<!DOCTYPE html> <html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AJAX GET 請求</title> <style> #result { width: 200px; height: 100px; border: solid 1px red; } </style> </head>
<body> <button>點擊發送請求</button> <div id="result"></div> </body> <script> const btn = document.getElementsByTagName('button')[0]; const result = document.getElementById('result'); btn.onclick = function () { //建立物件 const xhr = new XMLHttpRequest(); //初始化,設定請求方法和 URL xhr.open('GET', 'http://127.0.0.1:8000/servers?a=100&b=200'); //傳送 xhr.send(); //事件繫結,處理伺服器返回結果 //on when 當……。時候 //readystate 是xhr物件中的屬性,表示狀態0,1,2,3,4 //,0(沒有初始化),1(open方法呼叫完畢),2(send方法呼叫完畢),3(服務端返回了部分結果),4(服務端返回了所有結果) xhr.onreadystatechange = function () { //判斷服務端是否返回了所有結果 if (xhr.readyState == 4) { //判斷響應狀態是否成功(大於等於200小於300成功) if (xhr.status >= 200 && xhr.status < 300) { console.log(xhr.status);//狀態碼 console.log(xhr.statusText);//狀態字串 console.log(xhr.getAllResponseHeaders());//所有響應頭 console.log(xhr.response);//響應體 result.innerHTML = xhr.response } else {
} } } } </script>
</html> =======================post 請求體設定 ========================= <!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AJAX POST 請求</title> <style> #result { width: 200px; height: 100px; border: solid 1px red; } </style> </head>
<body> <div id="result"></div> </body> <script> const result = document.getElementById("result"); result.addEventListener("mouseover", function () { const xhr = new XMLHttpRequest(); xhr.open('POST', 'http://127.0.0.1:8000/servers'); //1、 xhr.send('a=100&b=200&c=300'); xhr.send('a:100&b:200&c:300'); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status >= 200 && xhr.status < 300) { result.innerText = xhr.response; } } } }) </script>
</html> =====================引數檢視==========================