我有一个简单的联系表格,然后我就可以从中发布。我正在尝试使用 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 完成之前卸载的。要解决此问题,您应该挂接到submit
事件的form
而不是单击按钮。然后你可以使用停止提交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");
}
});
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)