$_POST 在 ajax req 中为空



所以我正在尝试通过使用 AJAX 发送的表单上传文件,除了$_POST返回一个空数组($_FILES也是如此( - 尽管我不确定为什么。这是我表格的顶部:

HTML - 从PHP生成(在WP函数内部(

$html .= '<form method="post" class="form-horizontal" id="product-slides-form" enctype="multipart/form-data">';

阿贾克斯

//edit product gallery
$('#update-product-gallery').on('click', function()
{
var product_id       = $(this).data('id'),
slides_form      = $('#product-slides-form'),             
slides_form_data = new FormData(slides_form[0]);
//create array of slides
var slides  = {},
counter = 0;
$.each(slides_form.find('input'), function(j, v)
{
if ($(this)[0].files) {
$.each($(this)[0].files, function(i, files)
{
slides_form_data.append('slides-'+ counter, files);
counter++;
})
}
});
//add slideshow data
slides_form_data.append('slides', JSON.stringify(slides));
slides_form_data.append('product-id', product_id);
var slides_data = {};
slides_data['product_id']  = product_id;
slides_form_data.forEach(function(val, key)
{
slides_data[key] = val
});
//if I change data: to below test FormData than it works
var test = new FormData();
test.append('me', 1);
$.ajax({
data:        slides_data,
dataType:    'text',
type:        'post',
url:         PLUGIN_ROOT+ 'admin/inc/scripts/add-product-slides.php',
cache:       false,
contentType: false,
processData: false,
success:     function(res) {console.log(res)},
error:       function(res) {$.fn.showPopup(2, 'Something went wrong. Please try again.', res)}
})
});

我的脚本现在只是var_dumps$_POST+$_FILES

我使用以下命令控制台.log表单数据:

// Display the key/value pairs
for (var pair of slides_data.entries()) {
console.log(pair[0]+ ', ' + pair[1]); 
}

它返回正确的数据,所以我真的不确定为什么我的脚本没有获得$_POST数据?我错过了一些非常明显的东西吗?

(如果需要更多代码 - 评论,我会添加更多(

var slides_data = {};

这不是 FormData 对象。您需要发送一个 FormData 对象。

您可以在此处创建一个:

slides_form_data = new FormData(slides_form[0]);

继续对所有数据使用slides_form_data。不要创建第二个变量并忽略您为填充第一个变量所做的所有工作。

最新更新