js FormData All In One


js FormData All In One

query string & form data

js get data from formdata

https://developer.mozilla.org/en-US/docs/Web/API/FormData/values


var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

for (var value of formData.values()) {
   console.log(value);
}

https://developer.mozilla.org/en-US/docs/Web/API/FormData/get


var formData = new FormData();

formData.append('username', 'Chris');
formData.append('username', 'Bob');

formData.get('username');

solution

axios put & FormData 实现 重复 key


const params = {
    creative_id: "4838",
    creative_word_ids: "",
    description: ["zzz", 'abc'],
    title: ["111", '222'],
};

// 1. Object 转 FormData
const formData = new FormData();
// ReferenceError: FormData is not defined ? Web API

for (const [key, value] of Object.entries(params)) {
    if (Array.isArray(value)) {
        for (const item of value) {
            formData.append(key, item);
        }
    } else {
        formData.append(key, value);
    }
}

console.log('formData.toString() =', formData.toString());

for (const [key, value] of formData.entries()) {
    console.log('key, value =', key, value);
}

// 2. FormData 转 URLSearchParams
// const queryString = new URLSearchParams(forData);
// console.log('queryString.toString() =', queryString.toString());

// for (const [key, value] of queryString.entries()) {
//     console.log('key, value =', key, value);
// }

/*

? 实现 重复 key (title / description)

formData.toString() = [object FormData]
key, value = creative_id 4838
key, value = creative_word_ids
key, value = description zzz
key, value = description abc
key, value = title 111
key, value = title 222


*/
      

refs

https://github.com/xgqfrms/learning/issues/116#issuecomment-901721832


Flag Counter

?xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有??xgqfrms, 禁止转载 ???,侵权必究??!