简体   繁体   English

将 JSON 数组 object 附加到 formdata

[英]Appending JSON array object to formdata

I have a JSON array object called contacts:我有一个 JSON 数组 object 称为联系人:

var contacts = [];

After some processing the value of contacts look like:经过一些处理后, contacts的值如下所示:

[{ "Country":"country 1", "Phone":"123" },{ "Country":"country 2", "Phone":"456" }]

Now I want to add this to the "Contacts" name inside the formdata.现在我想将它添加到表单数据中的“联系人”名称中。 For that I use:为此,我使用:

var formdata = new FormData();
formdata.append("Contacts", JSON.stringify(contacts));

When I try alert(JSON.stringify(formdata));当我尝试alert(JSON.stringify(formdata)); on button click I get:在按钮点击我得到:

\"Contacts\":\"[{\\\"Country\\\":\\\"country 1\\\",\\\"Phone\\\":\\\"123\\\"},
{\\\"Country\\\":\\\"country 2\\\",\\\"Phone\\\":\\\"456\\\"}]\"}"

The problem is that in the API, its not detecting the list of contacts.问题是在 API 中,它没有检测到联系人列表。 I tried using POSTMAN as:我尝试使用 POSTMAN 作为:

Contacts[0].Country : country 1
Contacts[0].Phone : 123
Contacts[1].Country : country 2
Contacts[1].Phone : 456

API accepts data in that case. API 在这种情况下接受数据。 API accepts rest of the formdata fields except this, just sharing this info to rule out issue with api. API 接受除此之外的 formdata 字段的 rest,仅共享此信息以排除 api 的问题。

API accepts a collection of contacts as well as other fields like Name, Age and then Contacts. API 接受联系人集合以及其他字段,如姓名、年龄和联系人。

If your API accepts your data in that format, you cannot send it as JSON, you need to create a separate FormData entry for each of the lines you've mentioned.如果您的 API 接受该格式的数据,则不能将其作为 JSON 发送,您需要为您提到的每一行创建一个单独的FormData条目。

For example例如

const contacts = [{ "Country":"country 1", "Phone":"123" },{ "Country":"country 2", "Phone":"456" }];


var formdata = new FormData();

// This could be made fancier but it explains how to fix the problem
for (let i=0; i < contacts.length; i++) {
   formdata.append(`Contacts[${i}].Country`, contacts[i].Country);
   formdata.append(`Contacts[${i}].Phone`, contacts[i].Phone);
}

Note that json-form-data does it for you请注意, json-form-data为您完成

 const data = { Contacts: [{ "Country": "country 1", "Phone": "123" }, { "Country": "country 2", "Phone": "456" }] }; const formData = jsonToFormData(data); for (const [key,value] of formData.entries()) { console.log(`${key}: ${value}`); }
 <script src="https://unpkg.com/json-form-data@^1.7.0/dist/jsonToFormData.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM