How to use $.post with django?

我的未来我决定 提交于 2019-12-20 20:36:12

问题


How can I use the jquery.post() method in Django?

This is what I am trying to do:

         var postdata={
              'username':$('#login-email').val(), 
              'password':$('#login-password').val()
         }

         $.post('/login/',postdata)

How do I CSRF protect this in django? Is there a way to add to the CSRF token to the post data?


回答1:


I usually refer a file with this content to every page I want to be able to make AJAX requests:

if (!$)
    var $ = django.jQuery;

$('html').ajaxSend(function(event, xhr, settings) {
    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 = $.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});



回答2:


Yes. I believe it's stored in {{ csrf_token }}. So, just do

     var postdata={
          'username':$('#login-email').val(), 
          'password':$('#login-password').val(),
          'csrfmiddlewaretoken': '{{ csrf_token }}'
     }

You might have to double check the names, but that should be right.




回答3:


Although you didn't provide your html in your example is it safe to assume that you are using a <form>? If so, add your CSRF token template tag to your form and call .serialize() on your form.




回答4:


The contrib module in Django has a CSRF module that you can use.

As to your question how to send a POST, as long as you have the URL mapped properly requests will get sent to it. You can handle a POST request specifically by checking request.POST on the request object.



来源:https://stackoverflow.com/questions/5407463/how-to-use-post-with-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!