Post JSON data to an URL

The easiest way to do a POST in JavaScript: using fetch.

2 replies
  1. japanfever
    japanfever says:

    /* with jsfiddle’s echo replay */
    const $div = document.querySelector(‘div’);

    fetch(‘/echo/json/’, {
    method: ‘post’,
    body: “json=” + JSON.stringify({
    animal: ‘dog’
    })
    })
    .then(response => {
    if (response.ok) response.json().then(json => $div.textContent = JSON.stringify(json));
    else alert(response.statusText);
    });

    • Génesis
      Génesis says:

      Glad to see you here again 🙂 You are right, with your code we get the echo answer, JSFiddle web services need that ‘json=’ in the payload for that (they implemented it that way). However, I wanted it to keep it much simpler and generic. Thanks, you always write great comments xD

Comments are closed.