<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. The 'async' keyword indicates that this code is using asynchronous programming, which means that it is designed to run non-blocking code so that the user interface remains responsive while the request is being processed.</p>
JavaScript Form Submission and Server Communication: A Code Explanation

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

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