在Django视图中调用'request.POST'时,Ajax POST不发送数据

Eri*_*and 5 javascript django ajax jquery

我试图让Ajax POST将数据发送到我的视图,这样我就可以在那里操作我的数据,当我点击一个div类时up-arrow.

问题是,当我单击所述div并request.POST在我的视图文件中打印时,我得到一个POST包含的对象<QueryDict: {}>.空!我似乎无法弄清楚为什么我的POST请求没有发送我的数据.

这是我的HTML ...

{% for i in post.posts %}
    <li>
        <div>
            <div class='up-arrow'>
            </div>
            {{i}}
        </div>
    </li>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

这是我的AJAX/jQuery ......

$(document).ready(function(){
            $('.up-arrow').click(function(){
                $(this).hide()
                console.log('click')
                $.ajax({
                    headers: {
                        'Content-Type':'application/json',
                        'X-CSRFToken': getCookie('csrftoken')
                    },
                    url: 'voteuppost',
                    type: 'POST',
                    data: {'dane': 123456789101112},
                    success: function(data) {
                        alert('success!')   
                    },
                    error: function(){
                        alert('fail')
                    }

                })
                return false
            });
            function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        })
Run Code Online (Sandbox Code Playgroud)

这是我的看法......

class VoteUpPost(View):
    def post(self, request):
        print(request.POST)
        return JsonResponse({'status': True})
Run Code Online (Sandbox Code Playgroud)

这是我的网址路线......

    url(r'^voteuppost$', VoteUpPost.as_view()),
Run Code Online (Sandbox Code Playgroud)

我尝试过的事情......

1)我使用GET而不是,POST我能够使用获取数据值request.GET.get('dane')

1)尝试使用request.POST.datarequest.POST.DATA获得以下内容...... AttributeError: 'QueryDict' object has no attribute 'data' 我也得到了"失败" alert.

如何通过POST请求将数据发送到我的视图,然后访问其中的数据?

Pau*_*ulo 21

发布JSON数据时application/json需要使用request.body而不是request.POST.

像这样:

class VoteUpPost(View):
    def post(self, request):
        print(request.body)
        data = json.loads(request.body)
        return JsonResponse({'status': True})
Run Code Online (Sandbox Code Playgroud)

同样正如Jacques所提到的,请确保更新您的js以传递JSON字符串.

更改:

data: {'dane': 123456789101112},
Run Code Online (Sandbox Code Playgroud)

至:

data: JSON.stringify({'dane': 123456789101112}),
Run Code Online (Sandbox Code Playgroud)


Nav*_*avi 6

Django请求只能将application / x-www-form-urlencodedmultipart / form-data解析为request.POST。对于其他内容类型,您必须使用request.body属性。对于内容类型的断言,您可以从request.META.get('CONTENT_TYPE')

def sample_view(request):
    if request.META.get('CONTENT-TYPE') == 'application/json':
        data = json.loads(request.body)
        return JsonResponse({'any-message':'Hello'})
Run Code Online (Sandbox Code Playgroud)