简体   繁体   English

jQuery AJAX 没有错误或成功触发

[英]jQuery AJAX no error or success fired

I have a simple contact form then I am POST'ing out from.我有一个简单的联系表格,然后我要发帖了。 I am trying to AJAX the data with jQuery but for some reason I am not getting any response from the handlers.我正在尝试使用 jQuery 对数据进行 AJAX,但由于某种原因,我没有收到处理程序的任何响应。 Is this code correct?这段代码正确吗?

 $(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>

The problem is because you haven't stopped the default form submission (just the button click), so the page is actually unloading before the AJAX completes.问题是因为您没有停止默认的表单提交(只是单击按钮),所以页面实际上在 AJAX 完成之前正在卸载。 To fix this you should hook to the submit event of the form instead of the click of the button.要解决此问题,您应该挂钩formsubmit事件,而不是单击按钮。 Then you can stop the submission using preventDefault() .然后您可以使用preventDefault()停止提交。

Also note that you can use the serialize() method on the form to get the entered data instead of building your own object.另请注意,您可以使用表单上的serialize()方法来获取输入的数据,而不是构建您自己的对象。 Try this:尝试这个:

$(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");
            }
        });
    });
});

Try changing尝试改变

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

to

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