admin管理员组文章数量:1122846
const formData = new FormData();
const fields = {
title: bookingTitle,
image: image,
phone_number: phone || null
};
Object.entries(fields).forEach(([key, value]) => {
formData.append(key, value);
});
return formData;
}
I have a function that creates a FormData object, which handles both string and file inputs. One of the fields, phone_number, is optional, so I want to pass null when the user doesn't provide a value.
However, when I append null to the FormData object, it converts it to the string "null" instead of keeping it as a null value.
Since FormData is designed to handle strings and files, is there a way I can correctly represent phone_number as null or exclude it entirely when it's not provided?
const formData = new FormData();
const fields = {
title: bookingTitle,
image: image,
phone_number: phone || null
};
Object.entries(fields).forEach(([key, value]) => {
formData.append(key, value);
});
return formData;
}
I have a function that creates a FormData object, which handles both string and file inputs. One of the fields, phone_number, is optional, so I want to pass null when the user doesn't provide a value.
However, when I append null to the FormData object, it converts it to the string "null" instead of keeping it as a null value.
Since FormData is designed to handle strings and files, is there a way I can correctly represent phone_number as null or exclude it entirely when it's not provided?
Share Improve this question asked Nov 22, 2024 at 9:15 CodderCodder 373 bronze badges1 Answer
Reset to default 3The issue is because FormData.append()
coerces the provided value
argument to a string. Per MDN:
The field's value. This can be a string or Blob (including subclasses such as File). If none of these are specified the value is converted to a string.
To work around this you could send an empty string (which, depending on your server-side model binder, may be converted to null
).
phone_number: phone || ''
Alternatively you can avoid even sending the phone_number
property. You will then need your server-side logic to be more robust to handle the optional property:
const fields = {
title: bookingTitle,
image: image
};
if (phone)
fields.phone_number = phone;
本文标签: javascriptHow can i pass null as a value instead of quotnullquot in formDataStack Overflow
版权声明:本文标题:javascript - How can i pass null as a value instead of "null" in formData? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736304899a1932398.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论