繁体   English   中英

如何从我的 AJAX 帖子获取数据到我的 Django 视图?

[英]How do I get data from my AJAX Post to my Django View?

这就是我的 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 视图的样子。

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",

相反,它应该是一个视图的 url。

其次,ajax post 请求的头部应该有 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 视图中:

# 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'),
]

我无法添加评论,因为我还没有达到 StackOverflow 要求的 50 个声誉。 这应该是@abybaddi009 提供的答案下的评论。 到目前为止,他做得很好,但答案需要画龙点睛。

在视图中request_getdata = request.POST.get('getdata', None)不起作用,但这样做

body = request.body.decode('utf-8')
data = body[3]

request.body.decode('utf-8')返回一个类似于getdata=your_data的字符串,然后您可以使用字符串操作技术或正则表达式来提取数据。

我添加了 return false; 在 ajax 请求结束时,它起作用了。 我打印出视图中的值,而不是使用 HttpResponse。

你需要做的是:

ajax调用代码(在js文件中)将数据发送到视图

jQuery.ajax(
        {
            'url': "url_pattern_in_urls_py_file/",
            'type': 'POST',
            'contentType': 'application/json; charset=UTF-8',
            'data': JSON.stringify({'updated_data':your_data_val}),
            'dataType': 'json',
            'success': function ( return_data ) {
                
                                //success body
                
                              }
        }          
    );

django 视图中的代码关于上面的 POST ajax 调用以接收数据

import json

if request.method == 'POST':
   updatedData=json.loads(request.body.decode('UTF-8'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM