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

Django中Ajax POST请求返回None问题求助

问题解决方案

核心问题:你前端发送的是JSON格式的POST请求,但后端用request.POST.get()读取数据——request.POST只处理表单编码(application/x-www-form-urlencoded或multipart/form-data)的请求体,JSON格式的数据需要从request.body中解析。

步骤1:修改后端视图函数

导入json模块,解析请求体中的JSON数据:

import json
from django.http import HttpResponse

def newCoords(request):
    if request.method =='POST':
        # 解析JSON请求体(先把bytes转成字符串再解析)
        try:
            request_data = json.loads(request.body.decode('utf-8'))
        except json.JSONDecodeError:
            return HttpResponse("无效的JSON数据", status=400)
        
        # 从解析后的字典中取值
        pointName = request_data.get('pointName')
        fieldPoints = request_data.get('fieldPoints')
        print(pointName)
        print(fieldPoints)
        
        # 注意:如果fieldPoints是列表/字典类型,模型字段要对应JSONField
        point = points(pointName=pointName, fieldPoints=fieldPoints)
        point.save()
        print("alrighty then mate")
        
        return HttpResponse("200")
    else:
        print('well drats')
        return HttpResponse("how messed up is messed up")

步骤2:修复前端代码的小错误

你的JS代码有两处细节问题:

  • CSRF Token选择器多了方括号,应该修正为$('input[name=csrfmiddlewaretoken]').val()
  • 成功回调函数拼写错误:sucess → success

修正后的JS代码片段:

function sendList(maList,name) {
    var liste = maList;
    var namee= name;
    // 修正csrf token选择器
    var csrftoken = $('input[name=csrfmiddlewaretoken]').val();
    console.log(csrftoken);
    console.log(maList);
    console.log(name);
    $.ajax({
            type: "POST",
            url: "http://127.0.0.1:8000/home/newCoords/",
            headers: {
                'X-CSRFToken':csrftoken,
            },
            contentType:'application/json; charset=utf-8',
            dataType:'text',
            data: JSON.stringify({
                "pointName": namee,
                "fieldPoints": liste,
            }),
            // 修正拼写错误
            success: function() {
                console.log("请求成功");
            },
            error: function(xhr, status, error) {
                console.log(error);
            }
    });
}

步骤3:确保模型字段类型匹配

如果fieldPoints是列表/字典类型,你的points模型必须用JSONField存储,否则会存为空值:

from django.db import models

class points(models.Model):
    pointName = models.CharField(max_length=100)
    # 使用JSONField存储JSON类型数据(Django 3.1+支持)
    fieldPoints = models.JSONField()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:20:32