You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery发送POST请求创建博客文章,后端收到字节而非JSON数据

解决POST请求返回Python字节数据而非JSON的问题

嘿,我来帮你搞定这个问题!你遇到的核心问题是后端视图没有正确返回JSON格式的响应,导致前端拿到的是原始Python字节数据。咱们一步步来解决:

常见原因分析

后端返回字节数据通常是因为这两个原因:

  • 直接返回了Python字节对象(比如return b'{"status": "ok"}'),没有做JSON序列化和响应头设置
  • 没有将响应的Content-Type设置为application/json,jQuery无法自动解析为JSON对象

后端视图修复方案(以Django为例)

错误写法示例(导致字节返回)

def create_article(request):
    if request.method == 'POST':
        # 处理文章创建逻辑
        # 错误:直接返回字节数据
        return b'{"status": "success", "message": "文章已创建"}'

正确写法1:使用JsonResponse(推荐)

Django提供了JsonResponse类,会自动帮你序列化数据并设置正确的响应头:

from django.http import JsonResponse

def create_article(request):
    if request.method == 'POST':
        # 获取前端传来的title和description
        title = request.POST.get('title')
        description = request.POST.get('description')
        
        # 执行文章创建逻辑(比如保存到数据库)
        
        # 返回JSON响应
        response_data = {
            "status": "success",
            "message": "文章创建成功",
            "data": {"title": title, "description": description}
        }
        return JsonResponse(response_data)

正确写法2:手动序列化+设置响应头

如果不用JsonResponse,可以手动用json.dumps序列化数据,并指定Content-Type:

import json
from django.http import HttpResponse

def create_article(request):
    if request.method == 'POST':
        # 处理逻辑...
        
        response_data = {"status": "success"}
        # 序列化并设置Content-Type为application/json
        return HttpResponse(
            json.dumps(response_data),
            content_type="application/json"
        )

前端小提示

你的jQuery代码里已经指定了'json'作为响应类型,只要后端返回正确的JSON和响应头,jQuery会自动把响应解析成JSON对象,你可以在回调里直接使用:

$('#create-article').click(function(e){
    const title = $('#input-title').val();
    const description = $('#input-desc').val();
    const data = {title, description};
    
    $.post('/blog/create/', data, function(response) {
        // 这里的response已经是JSON对象了
        console.log(response.status);
        console.log(response.message);
    }, 'json');
    
    e.stopPropagation();
    e.preventDefault();
})

内容的提问来源于stack exchange,提问作者ohid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:09:17