Pedidos DELETE

Os pedidos DELETE são usados sempre que pretendemos eliminar dados no servidor.

Exemplo 1:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Delete aluno</title>
    <script>
      var xhr = new XMLHttpRequest();

      function showAluno() {
        if (xhr.readyState == 4 && xhr.status == 200) {
          const aluno = JSON.parse(xhr.responseText);
          const div = document.getElementById("show");
          div.innerHTML =
            aluno.nome + " - " + aluno.turma + " - aluno eliminado";
        }
      }

      function deleteAluno() {
        //define a função que vai receber e tratar a resposta:
        xhr.onreadystatechange = showAluno;
        //define o pedido:
        xhr.open("DELETE", "deleteAluno.php", true);
        xhr.setRequestHeader(
          "Content-type",
          "application/x-www-form-urlencoded"
        );
        //envia o pedido:
        xhr.send("nrAluno=7");
      }
    </script>
  </head>
  <body>
    <div id="show"></div>
    <hr />
    <button onclick="deleteAluno()">Delete aluno</button>
    <script>
      const bt = document.getElementById("bt");
    </script>
  </body>
</html>

No exemplo acima enviamos, num pedido DELETE, no formato form-urlencoded, o numero do aluno a eliminar e recebemos o objeto do aluno eliminado.

Exemplo 2:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Delete aluno</title>
    <script>
      var xhr = new XMLHttpRequest();

      function showAluno() {
        if (xhr.readyState == 4 && xhr.status == 200) {
          const aluno = JSON.parse(xhr.responseText);
          const div = document.getElementById("show");
          div.innerHTML =
            aluno.nome + " - " + aluno.turma + " - aluno eliminado";
        }
      }

      function deleteAluno() {
        const aluno = {
          nrAluno: "9",
        };
        //define a função que vai receber e tratar a resposta:
        xhr.onreadystatechange = showAluno;
        //define o pedido:
        xhr.open("DELETE", "deleteAlunoJson.php", true);
        // Content-Type header : JSON :
        xhr.setRequestHeader("Content-Type", "application/json");
        //envia o pedido:
        xhr.send(JSON.stringify(aluno));
      }
    </script>
  </head>
  <body>
    <div id="show"></div>
    <hr />
    <button onclick="deleteAluno()">Delete aluno</button>
    <script>
      const bt = document.getElementById("bt");
    </script>
  </body>
</html>

O exemplo acima é o mesmo que o Exemplo 1, com a diferença de que o numero do aluno é enviado para o servidor no formato JSON.