console.log(formData);
为空时,以下是我的代码。看不出它失败的原因。
$("#add_meal_item").on('click', '#save_meal_item', function () {
var meal_name = $("#add_meal_item_form").find('#meal_name').val();
var meal_type = $("#add_meal_item_form").find('#meal_type').val();
var logoImg = $("#add_meal_item_form").find('#meal_image').get(0).files[0];
var formData = new FormData();
formData.append('logo', logoImg);
formData.append('meal_type', meal_type);
formData.append('meal_name', meal_name);
console.log(formData);
var ajax_url = baseurl + '/save_meal_item';
$.ajax({
url: ajax_url,
type: 'POST',
data: formData,
success: function (response) {
}
});
});
答案 0 :(得分:2)
您需要先获取元素值,然后将它们附加到formData,如下所示:
var meal_name = $("#add_meal_item_form").find('#meal_name').val();
formData.append('meal_name ', meal_name );
要显示所有formData键和值,您必须使用FormData.entries方法:
for(var pair of formData.entries()) {
console.log(pair[0]+ ', '+ pair[1]);
}
答案 1 :(得分:2)
FormData.append()
不会为formData
创建可枚举属性,您需要使用FormData.entries中的迭代器来迭代这些值。
<强>演示强>
var formData = new FormData();
formData.append('logo', "11");
formData.append('meal_type', "22");
formData.append('meal_name', "33");
console.log(Object.keys(formData)); //[]
console.log(JSON.stringify(formData)); //{}
//use iterator
var formEntries = formData.entries();
//console.log(formEntries.next().value);
//console.log(formEntries.next().value);
//console.log(formEntries.next().value);
//or simply use Array.from
var formEntries = Array.from(formData.entries());
console.log("formEntries " , formEntries);