[英]Using jQuery to call an API, and then refresh the contents of the div containing the form?
我在div中有一个带有表单的页面。 提交表单将刷新div的包含页面。 当我提交表单时,jQuery不会中断表单的提交并执行。
我的代码:
<html>
<head>
<script src="/js/jquery.prod.2.2.0.js"></script>
<script>
$("#genericForm").on('submit', function(e) {
console.log("Here");
$.ajax({
type: "POST",
url: "/app.php";
data: $(this).serialize(),
success: function(data){
console.log(data);
}
});
e.preventDefault();
return false;
});
</script>
</head>
<body>
<form enctype="multipart/form-data" method=post action="/app.php" id="genericForm">
<input name=firstname type=text>
<input name=lastname type=text>
<input name=nickname type=text>
<input type=submit>
</form>
</body>
</html>
首先,您在这里遇到语法错误:
url: "/app.php";
您需要用逗号代替分号:
url: "/app.php",
另外,您需要将代码放入$(document).ready
事件处理程序中以使其工作。 当您在放置表单之前放置代码时,将立即执行该代码,该代码在DOM中找不到任何表单。 因此,以这种方式修复它:
$(document).ready(function () {
$("#genericForm").on('submit', function(e) {
console.log("Here");
$.ajax({
type: "POST",
url: "/app.php",
data: $(this).serialize(),
success: function(data){
console.log(data);
}
});
e.preventDefault();
return false;
});
});
语法错误
Uncaught SyntaxError: Unexpected token ;
中断submit handler
它与e.preventDefault();
无关e.preventDefault();
此处存在语法错误:
url: "/app.php";
______________^^
它必须是,
例如: url: "/app.php",
尝试这个:
$("#genericForm").on('submit', function(e) { e.preventDefault(); console.log("Here"); $.ajax({ type: "POST", url: "/app.php", data: $(this).serialize(), success: function(data) { console.log(data); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <form enctype="multipart/form-data" method=post action="/app.php" id="genericForm"> <input name=firstname type=text> <input name=lastname type=text> <input name=nickname type=text> <input type=submit> </form>
e.preventDefault
阻止元素的默认行为。 但是应该将其放置在执行任何其他任务之前,而不要使用默认功能。
$("#genericForm").on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/app.php";
data: $(this).serialize(),
success: function(data){
console.log(data);
}
});
});
正如Richard在评论中建议的那样,尝试将e.preventDefault()
移到函数顶部。 在注册e.preventDefault()
之前,可能会发生提交和刷新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.