How can I get form data with JavaScript/jQuery?

前端 未结 28 2214
不知归路
不知归路 2020-11-22 12:39

Is there a simple, one-line way to get the data of a form as it would be if it was to be submitted in the classic HTML-only way?

For example:



        
28条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 13:32

    It is 2019 and there's a better way to do this:

    const form = document.querySelector('form');
    const data = new URLSearchParams(new FormData(form).entries());
    

    or if you want a plain Object instead

    const form = document.querySelector('form');
    const data = Object.fromEntries(new FormData(form).entries());
    

    although note that this won't work with duplicate keys like you get from multi-select and duplicate checkboxes with the same name.

提交回复
热议问题