submit the form using ajax

后端 未结 8 888
栀梦
栀梦 2020-12-05 10:17

I\'m developing an application (a kind of social network for my university). I need to add a comment (insert a row in a specific database). To do this, I have a HTML form in

8条回答
  •  萌比男神i
    2020-12-05 10:55

    I would like to add a new pure javascript way to do this, which in my opinion is much cleaner, by using the fetch() API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.

    const formInputs = oForm.getElementsByTagName("input");
    let formData = new FormData();
    for (let input of formInputs) {
        formData.append(input.name, input.value);
    }
    
    fetch(oForm.action,
        {
            method: oForm.method,
            body: formData
        })
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.log(error.message))
        .finally(() => console.log("Done"));
    

    As you can see it is very clean and much less verbose to use than XMLHttpRequest.

提交回复
热议问题