通过html页面向后端传递JSON数据

代码实现

前端

<!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>

前端知识

最重要的两种请求方式:GETPOST
GET : 有请求参数,无请求体
POST : 有请求体,但也可以有请求参数

通过英语单词的命名,我们其实可以推测这两个方法适用于什么场景。
‘get’:获取查询数据库的内容,前端获取数据
‘post’:提交。前端提交数据,对数据库里的数据进行增删改

拿出我最近一直在看的开源项目renren-security,从swagger中可以更明显的对比GET和POST方法
在这里插入图片描述
无论是请求还是响应都具备四部分内容:请求行(响应行),请求头(响应头),空行,请求体(响应体)
抓包百度
在这里插入图片描述


请求头/响应头中有个重要header:content-type:它的作用是告诉接收方用什么方式来解析对应的body数据。
常见的有:application/x-wwwform-urlencoded(表单提交),text/plain(文本),application/json

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在 HTML 页面传递 JSON 数据到 Python 后端,可以使用 JavaScript 将 JSON 数据序列化为字符串,并将其作为 POST 请求的请求体发送到 Python 服务器。以下是一个简单的示例: HTML 页面: ```html <!DOCTYPE html> <html> <head> <title>传递JSON数据</title> </head> <body> <script> var data = { "name": "张三", "age": 20, "gender": "男" }; var xhr = new XMLHttpRequest(); xhr.open('POST', '/json_data'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify(data)); </script> </body> </html> ``` Python 服务器: ```python from flask import Flask, request app = Flask(__name__) @app.route('/json_data', methods=['POST']) def handle_json_data(): data = request.get_json() name = data['name'] age = data['age'] gender = data['gender'] return '姓名:{},年龄:{},性别:{}'.format(name, age, gender) if __name__ == '__main__': app.run(debug=True) ``` 在上面的示例中,JavaScript 将一个 JSON 对象序列化为字符串,并使用 XMLHttpRequest 对象向 `/json_data` 路径发送了一个 POST 请求,请求体为 JSON 字符串。在 Python 服务器中,`request.get_json()` 获取请求体中的 JSON 数据,然后使用这些数据返回一个简单的字符串响应。 需要注意的是,请求头中的 `Content-Type` 要设置为 `application/json`,表示请求体中包含 JSON 数据。在 Python 服务器中,可以使用 `request.get_json()` 方法获取 JSON 数据,Flask 会自动根据请求头中的 `Content-Type` 解析请求体中的数据

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高亚奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值