簡體   English   中英

使用jQuery調用API,然后刷新包含表單的div的內容?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM