我有一個通過AJAX發送數據到PHP腳本的聯繫表單。這是非常基本的,但我不能用序列化獲得輸入值。表單ID是正確的,我獲得輸入名稱,但不是它們的值。這是我的代碼。謝謝 !Jquery serialize()爲空
\t //Contact form AJAX
var form = $('#contact-form');
var formMessages = $('#form-messages');
// Serialize the form data.
\t var formData = $(form).serialize();
\t console.log($(form).serialize());
// Set up an event listener for the contact form.
\t $(form).submit(function(event) {
\t // Stop the browser from submitting the form.
\t event.preventDefault();
\t \t // Submit the form using AJAX.
\t \t $.ajax({
\t \t \t type: 'POST',
\t \t \t url: $(form).attr('action'),
\t \t \t data: formData
\t \t })
\t \t .done(function(response) {
\t \t \t // Make sure that the formMessages div has the 'success' class.
\t \t \t $(formMessages).hide().fadeIn();
\t \t \t $(formMessages).removeClass('error');
\t \t \t $(formMessages).addClass('success');
\t \t \t // Set the message text.
\t \t \t $(formMessages).text(response);
\t \t \t // Clear the form.
\t \t \t $('#form_name').val('');
\t \t \t $('#form_email').val('');
\t \t \t $('#form_message').val('');
\t \t })
\t \t .fail(function(data) {
\t \t \t // Make sure that the formMessages div has the 'error' class.
\t \t \t $(formMessages).hide().fadeIn();
\t \t \t $(formMessages).removeClass('success');
\t \t \t $(formMessages).addClass('error');
\t \t \t // Set the message text.
\t \t \t if (data.responseText !== '') {
\t \t \t \t $(formMessages).text(data.responseText);
\t \t \t } else {
\t \t \t \t $(formMessages).text("Something went wrong.");
\t \t \t }
\t \t });
\t });
<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>
https://jsfiddle.net/huja5pru/2/
好吧。這說得通。謝謝,當我僅在表單提交時序列化我的數據時才能正常工作。 – Quinox
很高興知道它的工作:) –