python - 如何从我的 AJAX 帖子获取数据到我的 Django View ?

标签 python ajax django

这是我的 ajax 调用的样子

$.ajax({
   url:"{% url 'handsontable' %}",     
   data: {'getdata': JSON.stringify(hot.getData())}, 
   dataType: 'json',
   type: 'POST',                                                                                                                                                                                                

   success: function (res, status) {
        alert(res);
        alert(status);
   },
   error: function (res) {
     alert(res.status);                                                                                                                          
   }
});

这是我的 Django View 的样子。

if request.method == 'POST':
    request_getdata = request.POST.get('getdata', 'None') 
    return HttpResponse(request_getdata)  

ajax 中的警报返回数据和“成功”。但是我的 HttpResponse 返回“无”。

知道为什么它不传递数据吗?谢谢!

最佳答案

首先你试图POST到一个html文件

url:"/utility_tool/decisions/solution_options/handsontable.html",

相反,它应该是 View 的 url。

其次,ajax post 请求的 header 中应包含 csrftoken,您可以这样设置:

<script type="text/javascript">
// using jQuery get csrftoken from your HTML
    var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            // if not safe, set csrftoken
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

    $.ajax({
        url: "{% url 'name of the view from urls.py' %}",
        data: {
            // here getdata should be a string so that
            // in your views.py you can fetch the value using get('getdata')
            'getdata': JSON.stringify(hot.getData())
        },
        dataType: 'json',
        success: function (res, status) {
            alert(res);
            alert(status);
        },
        error: function (res) {
            alert(res.status);                                                                                                                          
        }
    });
</script>

在你的 django View 中:

# views.py
from django.http import JsonResponse
def someView(request):

    if request.method == 'POST':
        # no need to do this
        # request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
        request_getdata = request.POST.get('getdata', None) 
        # make sure that you serialise "request_getdata" 
        return JsonResponse(request_getdata) 

在您的网址中:

# urls.py

urlpatterns = [
    # other urls
    path('some/view/', views.someView, name='name of the view in urls.py'),
]

关于python - 如何从我的 AJAX 帖子获取数据到我的 Django View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48793912/

相关文章:

python - 如何在Django模型中同步更新实例?

python - 让 Django 服务器在 EC2 实例上运行的正确方法是什么?

django - Celery 的 pytest 装置(celery_worker 和 celery_app)不起作用

python - Django:timezone.now 与 timezone.now()

python - 如何在基于DEAP的Python遗传算法中加入淘汰机制

javascript - 语法错误: unexpected token: identifier

javascript - Codeigniter 问题中的 Ajax

javascript - 响应式(Reactive) javascript - 将 ajax 调用转换为带有分页的 Bacon.js 流

python - 将新的 django rest 框架应用程序添加到设置

python - 如何在django中存储用户数组?