代码实现
前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Index</title>
<script src="{{ url_for("static", filename="jquery.js") }}"></script>
</head>
<body>
<br>
<h2 style="text-align: center;">机械臂动作测试</h2>
<div style="text-align: center;">
<br>
<input id="topic" type="text" placeholder="请输入主题"><br><br>
<input id="payload" type="text" placeholder="请输入内容"><br><br>
<button onclick="sendData()">发送表格数据</button>
<button onclick="sendData2()">机械臂动作</button>
</div>
<script>
function sendData() {
// 获取输入框中的数据
const topic = document.getElementById('topic').value;
const payload = document.getElementById('payload').value;
console.log(topic,payload);
// 将数据转换为json格式
const jsonData = JSON.stringify({"topic":topic,"payload":payload})
console.log("本次提交数据:",jsonData);
// 创建XMLHttpRequest对象
const xhr = new XMLHttpRequest();
// 设置POST请求,并指定后端接收数据的URL
xhr.open("POST", "/publish", true);
// 设置请求头,指定发送的数据类型为JSON
xhr.setRequestHeader("Content-Type", "application/json");
// 处理响应数据
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// 执行成功后,后端返回的数据
var response = JSON.parse(xhr.responseText);
console.log("本次提交响应的数据:",response);
} else if (xhr.readyState === 4) {
console.error('请求失败,服务器无响应');
}
};
// 发送请求,并将JSON数据作为请求体发送给后端
xhr.send(jsonData);
}
</script>
<script>
function sendData2() {
// 获取输入框中的数据
const topic = document.getElementById('topic').value;
const payload = document.getElementById('payload').value;
console.log(topic,payload);
// 将数据转换为json格式
const jsonData = JSON.stringify({"topic":topic,"payload":payload})
console.log("本次提交数据:",jsonData);
// 创建XMLHttpRequest对象
const xhr = new XMLHttpRequest();
// 设置POST请求,并指定后端接收数据的URL
xhr.open("POST", "/publish2", true);
// 设置请求头,指定发送的数据类型为JSON
xhr.setRequestHeader("Content-Type", "application/json");
// 处理响应数据
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// 执行成功后,后端返回的数据
var response = JSON.parse(xhr.responseText);
console.log("本次提交响应的数据:",response);
} else if (xhr.readyState === 4) {
console.error('请求失败,服务器无响应');
}
};
// 发送请求,并将JSON数据作为请求体发送给后端
xhr.send(jsonData);
}
</script>
</body>
</html>
前端知识
最重要的两种请求方式:GET、POST。
GET : 有请求参数,无请求体
POST : 有请求体,但也可以有请求参数
通过英语单词的命名,我们其实可以推测这两个方法适用于什么场景。
‘get’:获取。查询数据库的内容,前端获取数据
‘post’:提交。前端提交数据,对数据库里的数据进行增删改
拿出我最近一直在看的开源项目renren-security,从swagger中可以更明显的对比GET和POST方法
无论是请求还是响应都具备四部分内容:请求行(响应行),请求头(响应头),空行,请求体(响应体)
抓包百度
请求头/响应头中有个重要header:content-type:它的作用是告诉接收方用什么方式来解析对应的body数据。
常见的有:application/x-wwwform-urlencoded(表单提交),text/plain(文本),application/json