<!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使用</title>
<style>
.mainContainer {
font-size: 20px;
}
</style>
</head>
<body>
<div class="mainContainer">
<div>右键打开控制台查看ajax网络请求</div>
<button>点击发送GET请求</button>
<button>02点击发送带参数的GET请求</button>
<button>03点击发送带参数的POST请求</button>
</div>
<script>
const btn = document.getElementsByTagName('button')[0]
btn.onclick = function () {
const xhr = new XMLHttpRequest()
xhr.open('GET', 'http://127.0.0.1:8000/server')
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(`${btn.textContent}返回回来的数据:`, xhr.response)
} else {
console.log('接口请求失败', btn.textContent)
}
}
}
}
const btn2 = document.getElementsByTagName('button')[1];
btn2.onclick = function () {
const xhr = new XMLHttpRequest()
xhr.open('GET', 'http://127.0.0.1:8000/server/getAndValue?a=100&b=200&c=300');
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(`${btn2.textContent}返回回来的数据:`, xhr.response)
} else {
console.log('接口请求失败', btn2.textContent)
}
}
}
}
const btn3 = document.getElementsByTagName('button')[2];
btn3.onclick = function () {
const xhr = new XMLHttpRequest()
xhr.open('POST', 'http://127.0.0.1:8000/server/postAndValue');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('a=100&b=200&c=30000000000111')
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
console.log(`${btn3.textContent}返回回来的数据:`, xhr.response)
} else {
console.log('接口请求失败', btn3.textContent)
}
}
}
}
</script>
</body>
</html>