本文介绍了如何使用$ post与django?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Django中使用 jquery.post()
方法?
How can I use the jquery.post()
method in Django?
这就是我尝试做:
var postdata={
'username':$('#login-email').val(),
'password':$('#login-password').val()
}
$.post('/login/',postdata)
如何在django中CSRF保护?有没有办法添加到CSRF令牌到帖子数据?
How do I CSRF protect this in django? Is there a way to add to the CSRF token to the post data?
推荐答案
我通常将一个文件与此内容一起引用到每个页面我想要能够制作AJAX请求:
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'));
}
});
这篇关于如何使用$ post与django?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!