假设您有一个表单:
<form name="post" id="post-form" action="" method="post" enctype="multipart/form-data">
<input type="text" name="first_name">
<input type="text" name="last_name">
<input id="file" type="file" name="featured_image">
</form>
现在必须在ajax中将FormData对象传递给“data”参数
jQuery(document).ready(function($) {
$(\'#post-form\').submit(function(e) {
e.preventDefault();
var form = $(this);
file_data = $(\'#file\').prop(\'files\')[0]; //get the file
form_data = new FormData(); //form_data is a FormData() object
form_data.append(\'featured_image\', file_data); //append the file in form_data object
form_data.append(\'action\', \'insurance_form_data\'); // your wordpress function name
form_data.append(\'post_data\', form.serialize()); // e.g. other form data such as first_name, last_name will be stored as serialized
$.ajax({
url: \'/wp-admin/admin-ajax.php\',
type: \'POST\',
contentType: false,
processData: false,
data: form_data,
success: function(response) {
console.log(response);
},
error: function(xhr, status, error) {
console.log(error);
}
});
});
});
现在,在PHP文件中,您可以通过以下方式测试数据:
function insurance_form_data() {
print_r($_POST);
print_r($_FILES);
}