Come chiamare un'API del servizio Web REST da JavaScript?


166

Ho una pagina HTML con un pulsante su di essa. Quando faccio clic su quel pulsante, devo chiamare un'API del servizio Web REST. Ho provato a cercare online ovunque. Nessun indizio. Qualcuno può darmi un vantaggio / Headstart su questo? Davvero apprezzato.


La tua chiamata al servizio REST è solo una richiesta al server, immagino che sarà una richiesta Ajax. Usa jQuery per esempio api.jquery.com/jquery.ajax
ikos23

Risposte:


173

Sono sorpreso che nessuno abbia menzionato la nuova API Fetch, supportata da tutti i browser tranne IE11 al momento della stesura. Semplifica la sintassi XMLHttpRequest che vedi in molti degli altri esempi.

L'API include molto di più , ma inizia con il fetch()metodo. Sono necessari due argomenti:

  1. Un URL o un oggetto che rappresenta la richiesta.
  2. Oggetto init opzionale contenente il metodo, le intestazioni, il corpo ecc.

OTTIENI Semplice:

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
}

Ricreando la risposta principale precedente , un 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
}

2
Come si presenta l'azione del pulsante con questa soluzione?
asmaier

3
Che dire di DELETE e PUT?
Krzysztof,

2
@asmaier hai ricevuto una risposta su come apparirà l'azione del pulsante? Grazie
Angel Esguerra,

1
button.addEventListener('click', userAction);oppure<button onclick="userAction()" />
Brendan McGill il

105

Il tuo 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");
}

La tua azione Button ::

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

Per maggiori informazioni vai al seguente link (Aggiornato 2017/01/11)


19
XMLHttpRequest sincrono sul thread principale è obsoleto a causa dei suoi effetti dannosi per l'esperienza dell'utente finale. Per ulteriori informazioni xhr.spec.whatwg.org
jeet.chanchawat,

Dato che stai effettuando una chiamata sincronizzata, devi chiamare xhttp.open("POST", "Your Rest URL Here", false);, altrimenti xhttp.responseText non conterrà il risultato. Ma come detto prima, sarà presto deprecato.
Alexandre Fenyo,

Se questa è una richiesta POST, dove stai effettivamente pubblicando i dati?
EFC,

" xhttp.setRequestHeader("Content-type", "application/json");" - Questa è una bugia. Non stai passando alcun send()metodo JSON al metodo.
Quentin,

Hai modificato questo codice in modo che la richiesta non sia più sincrona, ma stai provando a leggere la risposta come se fosse.
Quentin,

17

Ecco un'altra chiamata API REST Javascript con autenticazione tramite 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>

non hai riscontrato problemi tra domini? Sto chiamando un API ospitato altrove da localhost e sta dando problemi tra domini.
Harit Vishwakarma,

Devo anche affrontare lo stesso problema con il corsetto ... per favore
Nitin Wahale il

@HaritVishwakarma - lo farà se l'API che stai chiamando non ha Access-Control-Allow-Origin per il tuo dominio (localhost). Prova a creare il tuo proxy, invia req al proxy e inoltra la richiesta alla tua destinazione. Poiché si tratterà di una comunicazione da server a server, la richiesta non verrà bloccata (CORS è bloccato dai browser). Invia questa risposta con l'intestazione allow-origin impostata su all
sss999 l'

@HaritVishwakarma e NitinWahale e gli sviluppatori futuri puoi disabilitare la sicurezza web sul tuo browser locale solo a scopo di test - questo non funzionerà come soluzione di produzione. Rif qui: stackoverflow.com/questions/3102819/…
KDT

12
    $("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);
        }
      });
});

8

Penso che aggiungere se (this.readyState == 4 && this.status == 200) aspettare è meglio:

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();

Non funzionerà se il client e l'API non si trovano nello stesso dominio, giusto?
David Brossard,

0

Prima di provare a mettere qualcosa sul front-end del sito Web, apriamo una connessione all'API. Lo faremo usando oggetti XMLHttpRequest, che è un modo per aprire file ed effettuare una richiesta HTTP.

Creeremo una variabile di richiesta e gli assegneremo un nuovo oggetto XMLHttpRequest. Quindi apriremo una nuova connessione con il metodo open () - negli argomenti specificheremo il tipo di richiesta come GET e l'URL dell'endpoint API. La richiesta viene completata e possiamo accedere ai dati all'interno della funzione di caricamento. Al termine, invieremo la richiesta.
// Crea una variabile di richiesta e assegna un nuovo oggetto XMLHttpRequest. var var = new XMLHttpRequest ()

// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)

request.onload = function () {
  // Begin accessing JSON data here
  }
}

// Send request
request.send()

1
Risposte simili sono state date in precedenza. Perché hai aggiunto la tua risposta? Una breve descrizione potrebbe essere d'aiuto
slfan il

-1

Il modo usuale è andare con PHP e ajax. Ma per le tue esigenze, di seguito funzionerà bene.

<body>

https://www.google.com/controller/Add/2/2<br>
https://www.google.com/controller/Sub/5/2<br>
https://www.google.com/controller/Multi/3/2<br><br>

<input type="text" id="url" placeholder="RESTful URL" />
<input type="button" id="sub" value="Answer" />
<p>
<div id="display"></div>
</body>

<script type="text/javascript">

document.getElementById('sub').onclick = function(){

var url = document.getElementById('url').value;
var controller = null; 
var method = null; 
var parm = []; 

//validating URLs
function URLValidation(url){
if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
var x = url.split('/');
controller = x[3];
method = x[4]; 
parm[0] = x[5]; 
parm[1] = x[6];
 }
}

//Calculations
function Add(a,b){
return Number(a)+ Number(b);
}
function Sub(a,b){
return Number(a)/Number(b);
}
function Multi(a,b){
return Number(a)*Number(b);
}  

//JSON Response
function ResponseRequest(status,res){
var res = {status: status, response: res};
document.getElementById('display').innerHTML = JSON.stringify(res);
}


//Process
function ProcessRequest(){

if(method=="Add"){
    ResponseRequest("200",Add(parm[0],parm[1]));
}else if(method=="Sub"){
    ResponseRequest("200",Sub(parm[0],parm[1]));
}else if(method=="Multi"){
   ResponseRequest("200",Multi(parm[0],parm[1]));
}else {
    ResponseRequest("404","Not Found");
 }

}

URLValidation(url);
ProcessRequest();

};
</script>
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.