js 以 json 格式 post form data

用 js 发起请求,以避免页面跳转

    <form action="/hello" method="POST" onsubmit="submitFormData(event)">
        <input type="text" name="name" required placeholder="username"><br>
        <input type="password" name="password" required placeholder="password"><br>
        <input type="submit" value="submit">
    </form>

    <form action="/world" method="POST" onsubmit="submitJson(event)">
        <input type="text" name="name" required placeholder="username"><br>
        <input type="password" name="password" required placeholder="password"><br>
        <input type="submit" value="submit">
    </form>


    <script type="text/javascript">
        function submitFormData(event) {
            event.preventDefault()

            const form = event.target

            fetch(form.action, {
                method: form.method,
                body: new FormData(form),
            })
            .then(async res => {
                if (res.ok) {
                    return await res.json()
                }
                return await Promise.reject(await res.text())
            })
            .then(res => console.log(res))
            .catch(error => console.error(error))
        }

        function submitJson(event) {
            event.preventDefault()

            const form = event.target

            const formData = new FormData(form)
            const formDataObject = Object.fromEntries(formData.entries())
            const formDataJsonString = JSON.stringify(formDataObject)

            fetch(form.action, {
                method: form.method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: formDataJsonString // body data type must match "Content-Type" header
            })
            .then(async res => {
                if (res.ok) {
                    return await res.json()
                }
                return await Promise.reject(await res.text())
            })
            .then(res => console.log(res))
            .catch(error => console.error(error))

        }
    </script>

https://www.section.io/engineering-education/how-to-format-form-data-as-json/#:~:text=Create an object from the formDatainstance using the,JSON body request and accepting JSON responses back.

posted on 2023-03-03 15:59  明天有风吹  阅读(467)  评论(0编辑  收藏  举报

导航

+V atob('d2h5X251bGw=')

请备注:from博客园