如何在jQuery端读取Django用marshal生成的字节字符串?
问题原因及解决方案
问题根源
marshal.dumps() 是Python专属的对象序列化工具,它生成的是Python内部二进制格式,并非符合标准的JSON字符串。前端jQuery默认会将content_type="application/json"的响应按标准JSON解析,自然无法识别marshal的二进制格式,导致解析乱码。
解决方法
直接使用标准JSON序列化方案替代marshal,有两种常用方式:
方式1:使用Python标准库json模块
import json from django.http import HttpResponse from django.urls import reverse def index(request): if request.method == 'POST': # ... 你的业务逻辑 settlement_id = 154 # 示例ID url = reverse('settlement_create', args=[settlement_id]) return HttpResponse(json.dumps({'url': url}), content_type="application/json")
方式2:使用Django内置的JsonResponse(推荐)
JsonResponse会自动处理JSON序列化和content_type设置,代码更简洁:
from django.http import JsonResponse from django.urls import reverse def index(request): if request.method == 'POST': # ... 你的业务逻辑 settlement_id = 154 # 示例ID url = reverse('settlement_create', args=[settlement_id]) return JsonResponse({'url': url})
为什么不推荐继续用marshal?
marshal是Python内部用于序列化代码对象(如.pyc文件)的工具,不适合跨语言数据交换,没有前端库支持解析marshal格式,完全没必要在前后端交互场景中使用它。
内容的提问来源于stack exchange,提问作者Roman Bolshevik
相关产品推荐
相关产品推荐

