我有一个自定义wordpress插件,它使用jquery和ajax来显示错误等,而无需重新加载页面。目前,ajax返回的数据是整个页面的html代码作为字符串。
我只会包含相关内容:
<form id="contactForm" enctype="multipart/form-data" action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post"></form>
和php:
// if the submit button is clicked, send the email
if ( isset( $_POST['cf-submitted'] ) ) {
$error = False;
if (empty($_POST["cf-name"])){
$nameError = "Name is required";
} else {
$name = sanitize_text_field( $_POST["cf-name"] );
}
// sanitize form values
$name = sanitize_text_field( $_POST["cf-name"] );
$email = sanitize_email( $_POST["cf-email"] );
$phone = "Phone: " . sanitize_text_field( $_POST["cf-phone"] );
$company = "Company: " . sanitize_text_field( $_POST["cf-company"] );
$deliverablesArr = $_POST["formDeliverables"];
$deliverables = "Deliverables: " . implode( $deliverablesArr);
$body = "Message Body: " . esc_textarea( $_POST["cf-body"] );
...等。等
// If email has been process for sending, display a success message
if ( !$error ) {
if ( wp_mail( $to, $subject, $message, $headers, $attachments ) ) {
echo '<div>';
echo '<p>Thanks for contacting us, expect a response soon.</p>';
echo '</div>';
if ($attachmentSet) {
print_r('attachment set');
//clean up your temp files after sending
foreach($attachments as $att) {
@unlink($att);
};
}
} else {
echo 'An unexpected error occurred';
}
}
和javascript:
// Set up an event listener for the contact form.
$(function() {
// Get the form.
var form = $('#contactForm');
// Get the messages div.
var formMessages = $('#messages');
$('#contactForm').submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// 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).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#company').val('');
$('#phone').val('');
$('#email').val('');
$('#projectDescription').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
不确定这里到底发生了什么。所有formData都是正确序列化的,我可以使用console.log。 ajax函数中发生的事情与我所拥有的不一致。还试图明确设置在ajax调用中使用的数据,但它根本不返回任何数据。只是一个空字符串。提前谢谢!