AJAX发送get请求
- 一、发送GET请求
- 二、设置请求参数
一、发送GET请求
1.创建html文件:
test.html中的内容:
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><title>Document</title></head><body><buttonid="btn">点击发送请求</button><divid="dd"></div><script>letbtn=document.getElementById("btn");letdd=document.getElementById("dd");//为按钮btn绑定单击事件btn.onclick=function(){// 1.创建对象constxhr=newXMLHttpRequest();//const设置常量// 2.初始化,设置请求方法'get'和url'http://127.0.0.1:8000'xhr.open("GET","http://127.0.0.1:8000");// 3.发送xhr.send();// 4.事件绑定,处理服务端返回的结果/*onreadystatechange注解: on:当……时候 readystate:是xhr对象中的属性,表示状态0 1 2 3 4 0.未初始化 1.open方法调用完毕 2.send方法调用完毕 3.服务端返回部分结果 4.服务端返回的所有结果 change:改变*/xhr.onreadystatechange=function(){// 判断(服务器返回的所有结果)if(xhr.readyState===4){// 判断响应状态码:200 401 403 500// 2xx 表示成功,所以status的范围是[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);//响应体dd.innerHTML=xhr.response;//将响应体中的内容添加到文本框dd中}}};};</script></body></html>test.js中的内容:
constexpress=require("express");constapp=express();app.get("/",(request,response)=>{response.setHeader("Access-Control-Allow-Origin","*");response.send("HELLO EXPRESS");});app.listen(8000,()=>{console.log("服务启动,800端口监听中……");});2.查看浏览器的显示结果:
二、设置请求参数
1.test.html中的内容:
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><title>Document</title></head><body><buttonid="btn">点击发送请求</button><divid="dd"></div><script>letbtn=document.getElementById("btn");letdd=document.getElementById("dd");btn.onclick=function(){constxhr=newXMLHttpRequest();// 设置请求参数a,b,cxhr.open("GET","http://127.0.0.1:8000?a=100&b=200&c=300");xhr.send();xhr.onreadystatechange=function(){if(xhr.readyState===4){if(xhr.status>=200&&xhr.status<300){dd.innerHTML=xhr.response;//将响应体中的内容添加到文本框dd中}}};};</script></body></html>test.js中的内容和上面相同。
2.查看浏览器的显示结果: