一尘不染

隐蔽表单数据到JSON字符串

json

<form name = 'test' >
    <input type='text' name = 'login'>
    <input type='email' name = 'email'>
</form>

如果我使用的话JSON.serialize($(form)).serializeArray();
我会得到[{"name":"login","value":"a value"},{"name":"email","value":"a email"}]需要的 {"login":"a login","email":"a email"} 。怎么做??


阅读 243

收藏
2020-07-27

共1个答案

一尘不染

您可以传递<form>FormData(),迭代键,FormData实例的值对,将每个键和值设置为对象的属性和值

let form = document.forms["test"];



let fd = new FormData(form);



let data = {};



for (let [key, prop] of fd) {

  data[key] = prop;

}



data = JSON.stringify(data, null, 2);



console.log(data);


<form name='test'>

  <input type='text' name='login' value="a login">

  <input type='email' name='email' value="a email">

</form>
2020-07-27