尝试在其中添加值时Javascript FormData为空
作者:互联网
以下是我执行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) {
}
});
});
解决方法:
您需要首先获取元素值,然后将它们附加到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]);
}
标签:form-data,javascript,jquery 来源: https://codeday.me/bug/20191025/1929507.html