1-GET.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ajax GET請求</title> <style> #result{ width:200px; height:100px; border:solid 1px #4fad09; } </style> </head> <body> <button>點擊發送請求</button> <div id="result"></div> <script> //獲取button元素 const btn=document.getElementsByTagName('button')[0]; const result=document.getElementById("result"); //綁定事件 btn.onclick=function(){ //1.創建對象 const xhr=new XMLHttpRequest(); //2.初始化 設置請求方法和url xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=200&c=300'); //3.發送 xhr.send(); //4.事件綁定 處理服務端返回的結果 //on即when:當...時候 //readystate是xhr對象中的屬性,表示狀態 0/1/2/3/4 //change改變 xhr.onreadystatechange=function(){ //判斷(服務端返回了所有結果) if(xhr.readyState===4){ //判斷響應狀態碼 200/404/403/401/500 //其中2xx均表示成功 if(xhr.status>=200 && xhr.status<300){ //處理結果:行 頭 空行 體 //1.響應行 console.log(xhr.status); //響應狀態碼 console.log(xhr.statusText); //響應狀態字符串 console.log(xhr.getAllResponseHeaders()); //所有響應頭 console.log(xhr.response); //響應體 //設置result的文本 result.innerHTML=xhr.response; } } } } </script> </body> </html>
2-POST.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ajax POST請求</title> <style> #result{ width:200px; height:100px; border:solid 1px #903; } </style> </head> <body> <div id="result"></div> <script> //獲取元素對象 const result=document.getElementById("result"); //綁定事件 result.addEventListener("mouseover",function(){ //1.創建對象 const xhr=new XMLHttpRequest(); //2.初始化 設置類型與URL xhr.open('POST','http://127.0.0.1:8000/server'); //設置請求頭 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.setRequestHeader('name','atguigu'); //3.發送 xhr.send('a=100&bb=200&c=300'); //4.事件綁定 xhr.onreadystatechange=function(){ //判斷 if(xhr.readyState===4){ if(xhr.status>=200&&xhr.status<300){ //處理服務端返回的結果 result.innerHTML=xhr.response; } } } }) </script> </body> </html>
server.js
//1.引入express const express=require('express'); //2.創建應用對象 const app=express(); //3.創建路由規則 //request是對請求報文的封裝 //response是對響應報文的封裝 app.get('/server',(request,response)=>{ //設置響應頭 允許跨域 response.setHeader('Access-Control-Allow-Origin','*'); //設置響應體 response.send('Hello Ajax GET'); }); app.all('/server',(request,response)=>{ //設置響應頭 允許跨域 response.setHeader('Access-Control-Allow-Origin','*'); //響應頭 response.setHeader('Access-Control-Allow-Headers','*'); //設置響應體 response.send('Hello Ajax POST'); }); //4.監聽端口啟動服務 app.listen(8000,()=>{ console.log("服務已經啟動,8000端口監聽中......"); })
啟動服務:

Ajax GET請求頁面:

Ajax POST請求頁面:(其中鼠標放在紅色框便會顯示Hello Ajax POST)

由上圖可見,增加了name屬性.
