我jQuery
功能看起来像
$(function() {
// activate "New" buttons if input is not empty
$('form input[type="text"]').live('keyup', function() {
var val = $.trim(this.value);
$(this).next("button").prop('disabled', val.length === 0);
});
$("body").on("submit","form",function(e){
// do not submit the form
e.preventDefault();
// handle everything yourself
var $form = $(this);
var title = $form.closest('.video-detail').find('.title').text();
var entryTitle = $form.find('.input-small').val();
console.debug(title);
console.debug(entryTitle);
$.ajaxSetup({
beforeSend: function(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 = 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;
}
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'));
}
}
});
// send the data to the server using .ajax() or .post()
$.ajax({
type: 'POST',
url: 'addVideo',
data: {
video_title: title,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
}).done(function(){
alert('done');
});
});
});
这是基于答案Django的CSRF检查与一个Ajax POST请求失败
我的html
看起来像
<form class="new-playlist form-inline" onclick="event.stopPropagation()">{% csrf_token %}
<input type="text" class="input-small">
<button class="btn btn-danger create-playlist-button" type="submit" disabled="disabled">New</button>
</form>
当我调试在Firefox的代码,我看到后值
csrfmiddlewaretoken {{ csrf_token }}
video_title The Who - Who Are You?
我怎样才能填充{{ csrf_token }}
值?
谢谢