我是一个通过AJAX将数据发送到PHP脚本的联系表单。它非常基本但我无法通过序列化获得输入值。表单ID是正确的,我获取输入名称,但不是他们的值。这是我的代码。谢谢!
//Contact form AJAX
var form = $('#contact-form');
var formMessages = $('#form-messages');
// Serialize the form data.
var formData = $(form).serialize();
console.log($(form).serialize());
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).hide().fadeIn();
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#form_name').val('');
$('#form_email').val('');
$('#form_message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).hide().fadeIn();
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text("Something went wrong.");
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="contact-form" class="col-md-12" method="post">
<h1>Contact</h1>
<fieldset class="form-group">
<input type="text" id="form_name" name="form_name" class="form-control" placeholder="Your name">
</fieldset>
<fieldset class="form-group">
<input type="email" id="form_email" name="form_email" class="form-control" placeholder="Your email" required>
</fieldset>
<fieldset class="form-group">
<textarea class="form-control" id="form_message" name="form_message" rows="3" placeholder="Your message" required></textarea>
</fieldset>
<button type="submit" class="btn btn-primary">Send</button>
</form>
&#13;
答案 0 :(得分:0)
Use serialize() method when form is submit.
check this fiddle https://jsfiddle.net/6o6htoh1/1/
答案 1 :(得分:0)
将jquery选择器用于jquery对象时出现语法错误,当您选择表单时,必须最近使用它,如下所示:
var form = $('#contact-form'); //and then use it directly in the ajax call like this
form.serialize(); // not $(form).serialize()
这是您的小提琴已更新https://jsfiddle.net/ingemi/kbpnmptw/您必须在ajax调用中直接使用序列化