我建議你使用Ajax。因爲在我們可以寫不同的情況來處理,如果提交成功與否。如果成功input.val('')else 顯示錯誤並且不乾淨輸入字段。
$('#post-form').on('submit', function(event){
event.preventDefault();
console.log("form submitted!") // sanity check
create_post();)}; function create_post() {
console.log("create post is working!")
$.ajax({
url : "/lrequestConfirmed/", // the endpoint
type : "POST", // http method
data : {
datef: $('#datepicker').val(),
type: $('#type').val(),
reason: $('#reason').val()
}, // data sent with the post request
// handle a successful response
success : function(json) {
$('#datepicker').val(''); // remove the value from the input
$('#reason').val('');
$('#results').html("<div class='alert alert-success alert-dismissable'><a href='#'' class='close' data-dismiss='alert' aria-label='close'>×</a><strong>Success!</strong> Your request has been recored</div>");
console.log(json); // log the returned json to the console
console.log("success"); // another sanity check
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert alert-danger alert-dismissable'><a href='#'' class='close' data-dismiss='alert' aria-label='close'>×</a><strong>Oops!</strong> Something went wrong</div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
在將它發送到服務器之前,在客戶端使用JavaScript進行驗證可能會更好 – AK47
在代碼中,如果表單數據無效,表單數據未清理,可能會在模板上執行某些操作。 –
AK45,我還沒有嘗試使用JavaScript進行驗證,但是如果我可以在服務器上這樣做,對我來說會更有趣,因爲我有一個額外的驗證,就是使用slug。 Bear Brown,我對模板做了一些修改,我沒有使用原始的Django表單,而是使用我自己的程式化的個性化表單。 –