无法将数据从JS AJAX发送回Django [英] Can't send data back to Django from JS AJAX

查看:91
本文介绍了无法将数据从JS AJAX发送回Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

html-javascript

html-javascript

    var csrftoken = $('[name="csrfmiddlewaretoken"]').val();

    $('#Save').click(function () {

        var ajaxdata = {
            exam: $('#Exam').val()
        };

        $.ajax({
            url: '/save',
            type: 'POST',
            dataType: 'json',
            data: JSON.stringify(ajaxdata),
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                "X-CSRFToken": csrftoken
            },
            credentials: 'include',
            success: function () {
                alert(ajaxdata);
                console.log(ajaxdata);
            },
            error:function (xhr, ajaxOptions, thrownError){
                console.log(ajaxdata);
            }
        });
    }

views.py

import json
from django.http import HttpResponse

def save(request=request):

    data = json.loads(request.body)

    testexam = data['exam']
    testexam = request.POST.get('exam')
    testobj = MyObject.objects.filter(name="David").first()
    testobj.Exam = testexam
    testobj.save()

return HttpResponse(json.dumps({"success": True}), content_type="application/json")

这些是我现在的html和视图.

These are my html and views now.

删除了烧瓶"部分.

data = json.loads(request.body)

允许我成功接收数据!

还是不太明白为什么"request.POST"不起作用.

Still don't quite understand why " request.POST " didn't work.

如果我设法知道原因,我会稍后再回来更新!

I'll come back later to update if I manage to know the reason!

感谢您的评论和有用的建议!

Thanks for the comments and useful suggestions!

推荐答案

无需使用烧瓶.

这是我接收数据的方式:

This is how I receive the data:

data = json.loads(request.body)

一切正常!

感谢所有评论,建议和答案!非常感谢!

Thanks for all the comments, suggestions, answers! Really appreciated!

这篇关于无法将数据从JS AJAX发送回Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆