Como chamar uma API de serviço web de descanso de JavaScript?

Tenho uma página HTML com um botão. Quando eu clicar nesse botão, Eu preciso chamar uma API Rest Web Service? Tentei pesquisar online em todo o lado. Não faço a mínima ideia. Alguém pode dar-me uma pista? Muito apreciado

Author: Jasper de Vries, 2016-05-02

5 answers

O Teu Javascript:

function UserAction() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
             alert(this.responseText);
         }
    };
    xhttp.open("POST", "Your Rest URL Here", true);
    xhttp.setRequestHeader("Content-type", "application/json");
    xhttp.send("Your JSON Data Here");
}

A acção do Botão:

<button type="submit" onclick="UserAction()">Search</button>

Para mais informações, consulte o seguinte link (actualizado em 2017/01/11)

 83
Author: Abhishek, 2018-07-26 10:26:56

Aqui está outra chamada de recuperação de Javascript com autenticação usando o json:

<script type="text/javascript" language="javascript">

function send()
{
    var urlvariable;

    urlvariable = "text";

    var ItemJSON;

    ItemJSON = '[  {    "Id": 1,    "ProductID": "1",    "Quantity": 1,  },  {    "Id": 1,    "ProductID": "2",    "Quantity": 2,  }]';

    URL = "https://testrestapi.com/additems?var=" + urlvariable;  //Your URL

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
    xmlhttp.open("POST", URL, false);
    xmlhttp.setRequestHeader("Content-Type", "application/json");
    xmlhttp.setRequestHeader('Authorization', 'Basic ' + window.btoa('apiusername:apiuserpassword')); //in prod, you should encrypt user name and password and provide encrypted keys here instead 
    xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
    xmlhttp.send(ItemJSON);
    alert(xmlhttp.responseText);
    document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<BR><textarea rows='100' cols='100'>" + xmlhttp.responseText + "</textarea>";
}

function callbackFunction(xmlhttp) 
{
    //alert(xmlhttp.responseXML);
}
</script>


<html>
<body id='bod'><button type="submit" onclick="javascript:send()">call</button>
<div id='div'>

</div></body>
</html>
 11
Author: user1713008, 2018-01-11 21:49:01
    $("button").on("click",function(){
      //console.log("hii");
      $.ajax({
        headers:{  
           "key":"your key",
     "Accept":"application/json",//depends on your api
      "Content-type":"application/x-www-form-urlencoded"//depends on your api
        },   url:"url you need",
        success:function(response){
          var r=JSON.parse(response);
          $("#main").html(r.base);
        }
      });
});
 5
Author: aayushi, 2017-03-01 18:11:34

Eu acho que adicione se (isto.readyState = = 4 & this.status = 200) esperar é melhor:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
        var response = xhttp.responseText;
        console.log("ok"+response);
    }
};
xhttp.open("GET", "your url", true);

xhttp.send();
 5
Author: martinwang1985, 2018-04-12 15:54:56
Surpreende-me que ninguém tenha mencionado a nova API Fetch, suportada por todos os navegadores, excepto a IE11 no momento da escrita. Simplifica a sintaxe XMLHttpRequest que você vê em muitos dos exemplos acima.

A API inclui muito mais , mas comece pelo método fetch(). São precisos dois argumentos:

  1. um URL ou um objecto que representa o pedido.
  2. objecto init opcional contendo o método, cabeçalhos, corpo, etc.

Simples GET:

const userAction = async () => {
  const response = await fetch('http://example.com/movies.json');
  const myJson = await response.json(); //extract JSON from the http response
  // do something with myJson
}

Recriando a resposta superior, um POST:

const userAction = async () => {
  const response = await fetch('http://example.com/movies.json', {
    method: 'POST',
    body: myBody, // string or object
    headers:{
      'Content-Type': 'application/json'
    }
  });
  const myJson = await response.json(); //extract JSON from the http response
  // do something with myJson
}
 5
Author: Brendan McGill, 2018-08-27 13:43:29