我正在嘗試爲我的Django表單實現AJAX表單提交。Ajax表單提交,未提交的文件
這些文件正在提交沒有AJAX,所以在服務器端的邏輯似乎正在工作。和ajax,其餘的值除了文件被提交。
下面是我實現的代碼,
AJAX表單提交
(function() {
// using jQuery
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;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
})();
jQuery的
$('#save-form').live('submit', function(event) { // catch the form's submit event
event.preventDefault();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: '/save/', // the file to call
success: function(response) { // on success..
$('#modalsave-form').html(response); // update the DIV
}
});
return false;
});
HTML表單
<form class="form-horizontal" id="save-form" enctype="multipart/form-data" method="post" action="/save/">
<div class="control-group">
<label class="control-label" for="id_body">Write Something</label>
<div class="controls">
<textarea class="typeaheadfun" id="id_body" rows="3" cols="100" name="body" placeholder="Scribble Body" style="width: 455px;"></textarea>
</div>
</div>
<div class="control-group">
<label class="control-label" for="id_media">Add a File</label>
<div class="controls">
<input type="file" name="media" id="id_media"/>
</div>
</div>
<hr>
<input class="btn btn-primary pull-right" type="submit" value="Post!" />
<br>
{% csrf_token %}
</form>
我已經問了這個問題。看看這裏http://stackoverflow.com/questions/14026889/django-file-upload-not-working-with-ajax 嘗試使用jquery表單插件 –
@RaunakAgarwal感謝您的評論:) jQuery表單插件太棒了! – Jonathan