如何将数据从AJAX文章获取到Django视图?

2024-05-19 21:38:36 发布

您现在位置:Python中文网/ 问答频道 /正文

这就是我的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返回“None”。

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


Tags: nonejsonurldatarequeststatusajaxfunction
3条回答

首先,您试图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'),
]

我不能添加评论,因为我还没有多达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。

相关问题 更多 >