Ajax请求基本操作
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');
//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>
响应头:
请求头:
响应体: