<script>
    const form = document.querySelector('form');
    const response = document.querySelector('#response');

    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        const prompt = formData.get('prompt');
        const res = await fetch('/', {
            method: 'POST',
            body: formData
        });
        const data = await res.json();
        response.value = data;
    });
</script>
<p>This code sets up an event listener on a form element that listens for a submit event. When the form is submitted, the code prevents the default action (i.e. reloading the page) using 'e.preventDefault()'. Then it creates a new 'FormData' object from the form data and extracts the value of a form field with the name 'prompt'.</p>
<p>Next, it sends a POST request to the current URL ('/') using the 'fetch()' method, passing the 'FormData' object as the request body. The response is then parsed as JSON using the 'json()' method, and the resulting data is set as the value of an HTML element with the ID 'response'.</p>
<p>Overall, this code is used to submit a form, send data to the server, and update the page with the server's response.</p>
<p>The code uses modern JavaScript syntax, such as the 'const' declaration and the 'async' and 'await' keywords, to make the code more concise and readable.</p>
JavaScript Form Submission with Fetch API and Server Response

原文地址: https://www.cveoy.top/t/topic/lBLB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录