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

Amr*_*non 7 python django ajax

这就是我的 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);                                                                                                                          
   }
});
Run Code Online (Sandbox Code Playgroud)

这就是我的 Django 视图的样子。

if request.method == 'POST':
    request_getdata = request.POST.get('getdata', 'None') 
    return HttpResponse(request_getdata)  
Run Code Online (Sandbox Code Playgroud)

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

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

aby*_*009 8

首先,您正在尝试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>
Run Code Online (Sandbox Code Playgroud)

在您的 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) 
Run Code Online (Sandbox Code Playgroud)

在你的网址中:

# urls.py

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


evu*_*eze 5

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

在视图中 request_getdata = request.POST.get('getdata', None)不起作用,但这确实有效

body = request.body.decode('utf-8')
data = body[3]
Run Code Online (Sandbox Code Playgroud)

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