$.post中加"json"和不加"json"之间的区别

本文探讨了在异步请求中,返回数据为JSON格式与字符串格式的区别。强调了使用JSON格式可以自动转换为JS对象,便于数据处理,而字符串格式则需手动转换。

不加的话刷新能显示也是通过这个异步获取数据吗?我猜不是。不加返回数据是默认格式(string),加了说明你要求返回的是json对象,即返回数据如果符合json格式会自动转成js的json对象,这样你在success回调中拿到的数据就是一个json对象,。你程序中的写法就是认为返回的是json对象,否则若是其它格式的数据,这样写是取不到值的。

不加的话需要用eval(’(’+result+’)’)将返回的json字符串转为json对象

# -*- coding: utf-8 -*- """ ============================ requests 课件:HTTP 请求核心方法详解 ============================ 版本:3.1 | 修复 JSON 解码错误 + 最佳实践示例 📌 使用的免费测试接口: 1. https://jsonplaceholder.typicode.com/ - 提供标准 REST API 接口 2. https://postman-echo.com/post - 稳定的 POST 测试接口,支持表单提交 """ # 🧠 What:requests 是什么? # requests 是 Python 中最常用的 HTTP 客户端库,用于向 Web 服务器发送各种类型的请求。 # 它广泛应用于 API 调试、接口测试、网络爬虫等场景。 # 🛠 How:怎么使用? # - 使用 requests.get() 发送 GET 请求 # - 使用 requests.post() 发送 POST 请求 # - 使用 requests.put() 发送 PUT 请求 # - 使用 requests.delete() 发送 DELETE 请求 # - 使用 params、data、json 控制请求体 # - 使用 headers 设置请求头 # - 使用 timeout 控制超时时间 # - 使用异常处理保障程序健壮性 # 🎯 Why:为什么要用 requests? # - 简洁易用,语法直观 # - 支持多种 HTTP 方法 # - 自动处理编码解码 # - 社区活跃,文档丰富 # - 适用于自动化脚本、接口测试、爬虫等 # -*- coding: utf-8 -*- """ ============================ requests 课件:HTTP 请求核心方法详解 ============================ 版本:3.1 | 修复 JSON 解码错误 + 最佳实践示例 """ import requests import json # 示例 1:最基础的 GET 请求 def demo_get_simple(): print("=== 示例 1:最基础的 GET 请求 ===") url = "http://127.0.0.1:5000/get" response = requests.get(url) print(f"状态码: {response.status_code}") print("响应内容(前50字符):") print(response.text[:50] + "...") # 示例 2:带查询参数的 GET 请求 def demo_get_with_params(): print("=== 示例 2:带查询参数的 GET 请求 ===") url = "http://127.0.0.1:5000/get" params = { "userId": 1, "_limit": 2 } response = requests.get(url, params=params) print(f"完整URL: {response.url}") result = response.json() print("服务器收到的查询参数:") for key, value in result['params'].items(): print(f"{key}: {value}") # 示例 3:带请求头的 GET 请求 def demo_get_with_headers(): print("=== 示例 3:带请求头的 GET 请求 ===") url = "http://127.0.0.1:5000/get" headers = { "User-Agent": "MyApp/1.0", "Accept": "application/json" } response = requests.get(url, headers=headers) result = response.json() print("请求头信息:") for key, value in result['headers'].items(): print(f"{key}: {value}") # 示例 4:带超时异常处理的 GET 请求 def demo_get_with_timeout(): print("=== 示例 4:带超时异常处理的 GET 请求 ===") url = "https://jsonplaceholder.typicode.com/posts" try: response = requests.get(url, timeout=3) response.raise_for_status() print("请求成功,返回数据条数:", len(response.json())) except requests.exceptions.Timeout: print("请求超时!") except requests.exceptions.HTTPError as e: print(f"HTTP 错误: {e}") except requests.exceptions.RequestException as e: print(f"请求错误: {e}") # 示例 5:最基础的 POST 请求(JSON 数据) def demo_post_simple_json(): print("=== 示例 5:最基础的 POST 请求(JSON 数据) ===") url = "http://127.0.0.1:5000/post-json" data = { "title": "新文章", "body": "这是内容", "userId": 1 } response = requests.post(url, json=data) result = response.json() print("服务器收到的 JSON 数据:") print(json.dumps(result['json'], indent=2)) # 示例 6:POST 发送表单数据(使用支持 form 数据返回的接口) def demo_post_form_data(): print("\n=== 示例 6:POST 发送表单数据 ===") url = "http://127.0.0.1:5000/post-form" form_data = { "username": "demo_user", "email": "user@example.com", "subscribe": "true", "preferences": "tech,news" } try: print(f"📤 发送的表单数据: {form_data}") response = requests.post(url, data=form_data, timeout=5) response.raise_for_status() result = response.json() print("\n✅ 服务器接收到的表单数据:") print(json.dumps(result['form'], indent=2)) print("\n🔍 请求详情:") print(f"请求头: {json.dumps(result['headers'], indent=2)[:100]}...") except requests.exceptions.RequestException as e: print(f"❌ 请求失败: {e}") except json.JSONDecodeError: print("❌ 响应不是有效JSON") print(f"原始响应: {response.text[:200]}") # 示例 7:POST 发送 JSON + 自定义 Headers def demo_post_json_with_headers(): print("=== 示例 7:POST 发送 JSON + 自定义 Headers ===") url = "http://127.0.0.1:5000/post-json" data = { "title": "高级文章", "body": "带自定义头", "userId": 1 } headers = { "Content-Type": "application/json", "X-Requested-With": "XMLHttpRequest" } response = requests.post(url, json=data, headers=headers) result = response.json() print("服务器收到的 JSON 数据:") print(json.dumps(result['json'], indent=2)) # 示例 8:POST 发送 JSON + 超时异常处理 def demo_post_with_timeout(): print("=== 示例 8:POST 发送 JSON + 超时异常处理 ===") url = "https://jsonplaceholder.typicode.com/posts" data = { "title": "测试超时", "body": "超时测试内容", "userId": 1 } try: response = requests.post(url, json=data, timeout=3) response.raise_for_status() print("创建成功,ID:", response.json()['id']) except requests.exceptions.Timeout: print("请求超时!") except requests.exceptions.RequestException as e: print(f"请求失败: {e}") # 示例 9:使用 PUT 请求更新资源 def demo_put_update(): print("=== 示例 9:使用 PUT 请求更新资源 ===") url = "http://127.0.0.1:5000/put" data = { "id": 1, "title": "更新后的标题", "body": "更新后的内容", "userId": 1 } response = requests.put(url, json=data) result = response.json() print(f"状态码: {response.status_code}") print("服务器收到的数据:") print(json.dumps(result['data'], indent=2)) # 示例 10:使用 DELETE 请求删除资源 def demo_delete_resource(): print("=== 示例 10:使用 DELETE 请求删除资源 ===") url = "http://127.0.0.1:5000/delete" response = requests.delete(url) print(f"状态码: {response.status_code}") print("服务器响应内容:", response.json()) # 示例 11:最佳实践 - 完整请求流程(headers + timeout + session + 异常处理) def demo_best_practice(): print("=== 示例 11:最佳实践 - 完整请求流程 ===") url = "http://127.0.0.1:5000/post-json" headers = { "User-Agent": "BestPracticeApp/1.0", "Accept": "application/json" } data = { "title": "最佳实践文章", "body": "这是一篇测试文章", "userId": 1 } with requests.Session() as session: session.headers.update(headers) try: response = session.post(url, json=data, timeout=5) response.raise_for_status() result = response.json() print("文章创建成功,提交的数据为:") print(json.dumps(result['json'], indent=2)) except requests.exceptions.Timeout: print("请求超时,请检查网络") except requests.exceptions.HTTPError as e: print(f"HTTP 错误: {e}") except requests.exceptions.RequestException as e: print(f"请求异常: {e}") # 主函数:运行所有示例 if __name__ == "__main__": print("🚀 开始演示 requests 核心请求方法详解") demo_get_simple() demo_get_with_params() demo_get_with_headers() demo_get_with_timeout() demo_post_simple_json() demo_post_form_data() demo_post_json_with_headers() demo_post_with_timeout() demo_put_update() demo_delete_resource() demo_best_practice() print("\n✅ 所有演示完成") 文件中加下注释,并且备注下,form-data json这两个 什么时候用哪个
最新发布
09-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值