How to prevent form from being submitted?

后端 未结 10 2342
挽巷
挽巷 2020-11-21 07:06

I have a form that has a submit button in it somewhere.

However, I would like to somehow \'catch\' the submit event and prevent it from occurring.

Is there s

10条回答
  •  感动是毒
    2020-11-21 07:33

    You can add eventListner to the form, that preventDefault() and convert form data to JSON as below:

    const formToJSON = elements => [].reduce.call(elements, (data, element) => {
      data[element.name] = element.value;
      return data;
    
    }, {});
    
    const handleFormSubmit = event => {
        event.preventDefault();
        const data = formToJSON(form.elements);
        console.log(data);
      //  const odata = JSON.stringify(data, null, "  ");
      const jdata = JSON.stringify(data);
        console.log(jdata);
    
        (async () => {
          const rawResponse = await fetch('/', {
            method: 'POST',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },
            body: jdata
          });
          const content = await rawResponse.json();
    
          console.log(content);
        })();
    };
    
    const form = document.forms['myForm']; 
    form.addEventListener('submit', handleFormSubmit);














提交回复
热议问题