写一个html单网页,居中显示一个按钮,功能为点击发送一个Post 设置单ip一小时之内只能请求3次 并解释请求方法原理及使用方法,请求头跟请求体应该怎么编辑
<!DOCTYPE html>
<html>
<head>
<title>Post请求限制</title>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.btn {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<button class="btn" onclick="sendPost()">发送Post请求</button>
</div>
<pre><code><script>
let count = 0;
function sendPost() {
if (count >= 3) {
alert('您已经请求了3次,不能再发送请求了!');
return;
}
// 创建XMLHttpRequest对象
let xhr = new XMLHttpRequest();
// 设置请求头
xhr.setRequestHeader('Content-Type', 'application/json');
// 监听请求状态变化
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
count++;
} else {
console.error(xhr.statusText);
}
}
}
// 设置请求体
let data = {ip: '127.0.0.1'};
xhr.send(JSON.stringify(data));
}
</script>
</code></pre>
</body>
</html>
<p>请求方法原理:通过XMLHttpRequest对象发送请求,监听请求状态变化,根据状态码判断请求是否成功,并处理返回的数据。</p>
<p>使用方法:点击页面中的按钮,即可发送Post请求。请求头需要设置Content-Type为application/json,请求体需传入一个JSON对象,其中包含要限制的IP地址。在请求状态为4(已完成)且状态码为200时,说明请求成功,可以在控制台中查看返回的数据。</p>
<p>请求头编辑:xhr.setRequestHeader('Content-Type', 'application/json');</p>
<p>请求体编辑:let data = {ip: '127.0.0.1'}; xhr.send(JSON.stringify(data));</p>
原文地址: https://www.cveoy.top/t/topic/skW 著作权归作者所有。请勿转载和采集!