我有一个问题,无论我使用Jquery和Ajax提交表单,但它仍然将我重定向到表单的操作页面,我不明白是否有影响函数或发生的事情。 这是我的代码:
<form action="add-niveau" method="POST" class="ajax">
<div>
<input type="text" name="name" placeholder="Your name">
</div>
<div>
<input type="text" name="email" placeholder="Your email">
</div>
<div>
<textarea rows="4" cols="20" name="comment"></textarea>
</div>
<input type="submit" value="send">
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"> </script>
<script>
$('form.ajax').on('submit', function() {
return false;
});
</script>
其他ajax脚本:
var ajaxRequest;
function ajaxFunction() {
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
}
function getForm(objButton) {
ajaxFunction();
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4) {
document.getElementById("formTag").innerHTML = ajaxRequest.responseText;
}
}
var buttonValue = objButton.value;
ajaxRequest.open("get", "get-form/" + buttonValue, true);
ajaxRequest.send(null);
}
// Send form using ajax:
$('form.ajax').on('submit', function(e) {
e.preventDefault();
});
答案 0 :(得分:0)
您需要添加event.preventDefault();在点击事件之后,因为您想要阻止默认表单提交。
$('form.ajax').on('submit', function(event) { // pass the event to function
event.preventDefault(); // add this line
$.ajax({
url: "test.php",
context: document.body
}).done(function() {
alert('Done!');
});
});