如果你想避免处理表单,我建议使用 jquery 的 $.ajax() 方法。基本上,您只需要创建一个空白表单模型来捕获 POST,然后您就可以获取数据并按照您的意愿使用它。这是一个例子:
#models.py
class BlankForm(forms.Form):
def __unicode__(self):
return "BlankForm"
#views.py
def my_view(request):
if request.method == 'POST':
if 'answer' in request.POST:
form = BlankForm(request.POST)
if form.is_valid():
foo = request.POST.__getitem__('add')
bar = request.POST.__getitem__('bar')
baz = request.POST.__getitem__('baz')
#Do stuff with your data:
return HttpResponse('ok')
然后在您的网页中,您可以使用以下内容:
<script type="text/javascript">
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]);
// 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;
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
var csrftoken = getCookie('csrftoken');
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
type: 'POST',
data: {
'answer': true,
'foo': foo,
'bar': bar,
'baz': baz
},
dataType: 'application/json'
});
}
</script>
所有关于 cookie 和 CSRF 令牌的东西都与 django 的 CSRF 保护系统有关。基本上,您需要担心的只是编辑 $.ajax() 方法中的 Data 字段