我正在开发我的Django应用程序,我想使用JavaScript来改进我的网站。
我有一张表格,我想展示两件事:
这是我第一次使用JS,我需要帮助来完成这个过程。
这是我的代码:
<form class = "form" method='POST' action=''> {% csrf_token %}
<br></br>
{{ form.as_p}}
<br></br>
<button type="submit">Valider</button>
</form>
<script>
$('#form').submit(function() {
var c = confirm("Click OK to continue?");
return c; //you can just return c because it will be true or false
});
</script>
如果我的表格有效并保存:
<script type="text/javascript" >
$(document).on('Valider', 'form.form', function(form) {
var $form = $(form);
$.ajax({
url:"/path_to_my_html_file/BC_form2.html",
type: "POST",
success: function(form) {
alert("Form is saved");
}
});
});
</script>
你能帮帮我吗?
谢谢
答案 0 :(得分:1)
您可以尝试使用此代码:
$('#form').submit(function(e) {
// Prevents form to be submitted by default post request with page reloading
e.preventDefault();
if (confirm("Click OK to continue?")) {
// Here you can call your AJAX request
callAjax($('input[type=text]').val())
}
});
function callAjax(value) {
// Making AJAX request to your endpoint
// GET ipify just for example
$.ajax({
url:"https://api.ipify.org?format=json",
type: "GET",
success: function(form) {
alert("Form is saved");
}
});
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input type="hidden" value="MOCK FOR CSRF TOKEN" />
<br></br>
<input type="text" required />
<br></br>
<button type="submit">Valider</button>
</form>
&#13;
答案 1 :(得分:0)
在提交功能中使用.valid()
$('#form').submit(function() {
var isValid=$("#form").valid();
if (isValid) { //If there is no validation error
var c = confirm("Click OK to continue?");
if(c){
$.ajax({
url:"/path_to_my_html_file/BC_form2.html",
type: "POST",
success: function(form) {
alert("Form is saved");
}
});
}
}
else {
alert('form is not valid');
}
});
</script>