[英]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.