簡體   English   中英

jQuery AJAX 沒有錯誤或成功觸發

[英]jQuery AJAX no error or success fired

我有一個簡單的聯系表格,然后我要發帖了。 我正在嘗試使用 jQuery 對數據進行 AJAX,但由於某種原因,我沒有收到處理程序的任何響應。 這段代碼正確嗎?

 $(document).on("ready", function() { $("#contactButton").on("click", function(e) { e.preventDefault(); var data = { clientName: $("input").eq(1).val(), clientEmail: $('input').eq(2).val(), clientMessage: $('textarea').val() }; $.ajax({ type: 'POST', url: 'email.php', data: data, dataType: 'json', success: function(response) { $("#contactButton").text("Thank You"); $("input").val(""); $("textarea").val(""); }, error: function(response) { alert("Error: Message Not Sent"); } }); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="contact"> <input type="text" name="clientName" placeholder="Name" required> <input type="email" name="clientEmail" placeholder="Email" required> <textarea name="clientMessage" required>Message</textarea> <button id="contactButton">Contact</button> </form>

問題是因為您沒有停止默認的表單提交(只是單擊按鈕),所以頁面實際上在 AJAX 完成之前正在卸載。 要解決此問題,您應該掛鈎formsubmit事件,而不是單擊按鈕。 然后您可以使用preventDefault()停止提交。

另請注意,您可以使用表單上的serialize()方法來獲取輸入的數據,而不是構建您自己的對象。 嘗試這個:

$(document).on("ready", function() {
    $("#contact").on("submit", function(e) {
        e.preventDefault();

        $.ajax({
            type: 'POST',
            url: 'email.php',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(response){
                $("#contactButton").text("Thank You");
                $("input").val("");
                $("textarea").val("");
            }, 
            error: function(response){
                alert("Error: Message Not Sent");
            }
        });
    });
});

嘗試改變

var data = {
    clientName: $("input").eq(1).val(),
    clientEmail: $('input').eq(2).val(),
    clientMessage: $('textarea').val()
};

var data = {
    'clientName': $("input").eq(1).val(),
    'clientEmail': $('input').eq(2).val(),
    'clientMessage': $('textarea').val()
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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