我在Wordpress模板中製作了一個表單,該表單進行了某些計算並在模態引導程序中顯示結果。如何在不刷新頁面的情況下發送表單
HTML:
//FORM
<form method="post" id="myForm">
<span>Name</span><br><input type="text" name="name" id="name" required>
<span>Email</span><br>
<input type="email" name="email" id="email" required>
<span>Altura</span><br>
<input type="number" name="altura" id="altura" required>
<span>Peso</span><br>
<input type="number" name="peso" id="peso" required>
<br><br>
<button type="submit" id="enviar" onclick="calcularIMC();">Enviar</button>
//MODAL
<div class="modal fade" id="ajax-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div id="corpo_modal">
<p> ALL FIELDS </p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JAVASCRIPT:
function calcularIMC(){
var nome = document.getElementById("nome").value;
var email = document.getElementById("email").value;
var estilo = document.getElementById("estilo").value;
var experiencia = document.getElementById("experiencia").value;
var altura = document.getElementById("altura").value;
var peso = document.getElementById("peso").value;
var resultado = 5;
var corpo = document.getElementById("corpo_modal");
var imc = 0;
if(altura >0 && peso >0){
imc = peso/(altura * altura);
}
if(estilo == "Surf"){
if((imc<=25) && (resultado == 5)){
corpo.innerHTML = '<img src="1.png" style="width: 150px; height:150px">';
}
else{
corpo.innerHTML = '<img src="2.png" style="width: 150px; height:150px">';
}
}
else if(estilo == "SUP"){
if((experiencia >= 3) && (imc <=29)){
corpo.innerHTML = '<img src="3.png" style="width: 150px; height:150px">';
} else{
corpo.innerHTML = '<img src="4.png" style="width: 150px; height:150px">';
}
}
}
的問題是,當我發送的形式,它更新頁面和不顯示模式。
經過一番研究,我發現要解決這個問題,我需要使用Ajax - jQuery.ajax。
我發現這個代碼:
$(function() {
$('form#myForm').on('submit', function(e) {
$.post('', $(this).serialize(), function (data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
}).error(function() {
// This is executed when the call to mail.php failed.
});
e.preventDefault();
});
});
當我創建一個單獨的頁面形式,根本不把在WordPress模板,它的工作原理。但是當我將代碼放在wordpress模板中時,它會在3秒後更新頁面。
我還發現,我可以在jquery
,功能$.ajax();
使用原生功能ajax
和自己的內部我用標籤,如url
,type
,data
等。我是阿賈克斯的初學者,我迷失在如何做到這一點。
爲什麼功能
e.preventDefaul();
不工作,當我把wordpress模板?有可能讓它在wordpress模板中工作?
或
我如何使用
$.ajax()
來解決這個問題?
我想發送表單而不刷新頁面!
有你包括jQuery庫? –
是啊!肯定是的。只是發佈沒有找到必要 – Zkk