如何从我的AJAX Post获取数据到我的Django View?

时间:2018-02-14 18:27:13

标签: 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视图。

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

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

知道为什么它没有通过数据?谢谢!

4 个答案:

答案 0 :(得分:2)

首先,您正在尝试POST到html文件

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

相反,它应该是视图的网址。

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我无法添加评论,因为我还没有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的字符串,然后可以使用字符串处理技术或正则表达式提取数据。

答案 3 :(得分:0)

您需要做的是:

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
                
                              }
        }          
    );
关于以上POST ajax调用的django视图中的

代码以接收数据

import json

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