Domanda

Devo fare una HTTP GET in JavaScript. Qual è il modo migliore per farlo?

Devo farlo in un widget dashcode di Mac OS X.

È stato utile?

Soluzione

I browser (e Dashcode) forniscono un oggetto XMLHttpRequest che può essere utilizzato per effettuare richieste HTTP da JavaScript:

function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

Tuttavia, le richieste sincrone sono scoraggiate e genereranno un avviso lungo le linee di:

  

Nota: a partire da Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), le richieste sincrone sul thread principale sono state deprecate a causa degli effetti negativi sull'esperienza utente.

È necessario effettuare una richiesta asincrona e gestire la risposta all'interno di un gestore eventi.

function httpGetAsync(theUrl, callback)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() { 
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", theUrl, true); // true for asynchronous 
    xmlHttp.send(null);
}

Altri suggerimenti

In jQuery :

$.get(
    "somepage.php",
    {paramOne : 1, paramX : 'abc'},
    function(data) {
       alert('page content: ' + data);
    }
);

Un sacco di ottimi consigli sopra, ma non molto riutilizzabili, e troppo spesso pieni di assurdità DOM e altra lanugine che nasconde il codice semplice.

Ecco una classe Javascript che abbiamo creato, riutilizzabile e facile da usare. Attualmente ha solo un metodo GET, ma funziona per noi. L'aggiunta di un POST non dovrebbe tassare le competenze di nessuno.

var HttpClient = function() {
    this.get = function(aUrl, aCallback) {
        var anHttpRequest = new XMLHttpRequest();
        anHttpRequest.onreadystatechange = function() { 
            if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
                aCallback(anHttpRequest.responseText);
        }

        anHttpRequest.open( "GET", aUrl, true );            
        anHttpRequest.send( null );
    }
}

Usarlo è facile come:

var client = new HttpClient();
client.get('http://some/thing?with=arguments', function(response) {
    // do something with response
});

Una versione senza callback

var i = document.createElement("img");
i.src = "/your/GET/url?params=here";

Il nuovo window.fetch L'API è un sostituto più pulito di XMLHttpRequest che utilizza le promesse di ES6. C'è una bella spiegazione qui , ma si riduce a (dall'articolo):

fetch(url).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
}).catch(function() {
  console.log("Booo");
});

Il supporto del browser è ora valido nelle ultime versioni (funziona in Chrome, Firefox, Edge (v14 ), Safari (v10.1), Opera, Safari iOS (v10.3), browser Android e Chrome per Android), tuttavia IE probabilmente non riceverà supporto ufficiale. GitHub ha un polyfill che è raccomandato per supportare i browser più vecchi ancora ampiamente in uso (esp versioni di Safari pre marzo 2017 e browser mobili dello stesso periodo).

Suppongo che questo sia più conveniente di jQuery o XMLHttpRequest o meno dipende dalla natura del progetto.

Ecco un link alla specifica https://fetch.spec.whatwg.org/

Modifica :

Usando ES7 async / await, questo diventa semplicemente (basato su this Gist ):

async function fetchAsync (url) {
  let response = await fetch(url);
  let data = await response.json();
  return data;
}

Ecco il codice per farlo direttamente con JavaScript. Ma, come accennato in precedenza, saresti molto meglio con una libreria JavaScript. Il mio preferito è jQuery.

Nel caso seguente, viene richiamata una pagina ASPX (che fa parte del servizio REST di un uomo povero) per restituire un oggetto JSON JavaScript.

var xmlHttp = null;

function GetCustomerInfo()
{
    var CustomerNumber = document.getElementById( "TextBoxCustomerNumber" ).value;
    var Url = "GetCustomerInfoAsJson.aspx?number=" + CustomerNumber;

    xmlHttp = new XMLHttpRequest(); 
    xmlHttp.onreadystatechange = ProcessRequest;
    xmlHttp.open( "GET", Url, true );
    xmlHttp.send( null );
}

function ProcessRequest() 
{
    if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) 
    {
        if ( xmlHttp.responseText == "Not found" ) 
        {
            document.getElementById( "TextBoxCustomerName"    ).value = "Not found";
            document.getElementById( "TextBoxCustomerAddress" ).value = "";
        }
        else
        {
            var info = eval ( "(" + xmlHttp.responseText + ")" );

            // No parsing necessary with JSON!        
            document.getElementById( "TextBoxCustomerName"    ).value = info.jsonData[ 0 ].cmname;
            document.getElementById( "TextBoxCustomerAddress" ).value = info.jsonData[ 0 ].cmaddr1;
        }                    
    }
}

Una versione pronta per copia e incolla

let request = new XMLHttpRequest();
request.onreadystatechange = function () {
    if (this.readyState === 4) {
        if (this.status === 200) {
            document.body.className = 'ok';
            console.log(this.responseText);
        } else if (this.response == null && this.status === 0) {
            document.body.className = 'error offline';
            console.log("The computer appears to be offline.");
        } else {
            document.body.className = 'error';
        }
    }
};
request.open("GET", url, true);
request.send(null);

IE memorizzerà nella cache gli URL per velocizzare il caricamento, ma se, ad esempio, esegui il polling di un server a intervalli cercando di ottenere nuove informazioni, IE memorizzerà nella cache tale URL e probabilmente restituirà lo stesso set di dati che hai sempre avuto.

Indipendentemente da come finisci per fare la tua richiesta GET - JavaScript vanilla, prototipo, jQuery, ecc. - assicurati di mettere in atto un meccanismo per combattere la cache. Per combatterlo, aggiungi un token univoco alla fine dell'URL che stai per colpire. Questo può essere fatto da:

var sURL = '/your/url.html?' + (new Date()).getTime();

Ciò aggiungerà un timestamp univoco alla fine dell'URL e impedirà che si verifichi la memorizzazione nella cache.

Breve e puro:

const http = new XMLHttpRequest()

http.open("GET", "https://api.lyrics.ovh/v1/toto/africa")
http.send()

http.onload = () => console.log(http.responseText)

Prototype rende semplice la morte

new Ajax.Request( '/myurl', {
  method:  'get',
  parameters:  { 'param1': 'value1'},
  onSuccess:  function(response){
    alert(response.responseText);
  },
  onFailure:  function(){
    alert('ERROR');
  }
});

Non ho familiarità con i widget Dashcode di Mac OS, ma se ti consentono di utilizzare le librerie JavaScript e supportano XMLHttpRequests , utilizzerei jQuery e farei qualcosa del genere :

var page_content;
$.get( "somepage.php", function(data){
    page_content = data;
});

Una soluzione che supporta browser meno recenti:

function httpRequest() {
    var ajax = null,
        response = null,
        self = this;

    this.method = null;
    this.url = null;
    this.async = true;
    this.data = null;

    this.send = function() {
        ajax.open(this.method, this.url, this.asnyc);
        ajax.send(this.data);
    };

    if(window.XMLHttpRequest) {
        ajax = new XMLHttpRequest();
    }
    else if(window.ActiveXObject) {
        try {
            ajax = new ActiveXObject("Msxml2.XMLHTTP.6.0");
        }
        catch(e) {
            try {
                ajax = new ActiveXObject("Msxml2.XMLHTTP.3.0");
            }
            catch(error) {
                self.fail("not supported");
            }
        }
    }

    if(ajax == null) {
        return false;
    }

    ajax.onreadystatechange = function() {
        if(this.readyState == 4) {
            if(this.status == 200) {
                self.success(this.responseText);
            }
            else {
                self.fail(this.status + " - " + this.statusText);
            }
        }
    };
}

Forse un po 'eccessivo ma sicuramente vai al sicuro con questo codice.

Utilizzo:

//create request with its porperties
var request = new httpRequest();
request.method = "GET";
request.url = "https://example.com/api?parameter=value";

//create callback for success containing the response
request.success = function(response) {
    console.log(response);
};

//and a fail callback containing the error
request.fail = function(error) {
    console.log(error);
};

//and finally send it away
request.send();

Nel file Info.plist del widget, non dimenticare di impostare la chiave AllowNetworkAccess su true.

Il modo migliore è usare AJAX (puoi trovare un semplice tutorial in questa pagina Tizag ). Il motivo è che qualsiasi altra tecnica che è possibile utilizzare richiede più codice, non è garantito il funzionamento tra browser senza rielaborazione e richiede l'utilizzo di più memoria client aprendo pagine nascoste all'interno di frame passando gli URL che analizzano i loro dati e chiudendoli. AJAX è la strada da percorrere in questa situazione. Che i miei due anni di sviluppo pesante javascript parlando.

Per coloro che usano AngularJs , è $ http .get :

$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

Puoi ottenere una richiesta HTTP GET in due modi:

  1. Questo approccio si basa sul formato xml. Devi passare l'URL per la richiesta.

    xmlhttp.open("GET","URL",true);
    xmlhttp.send();
    
  2. Questo è basato su jQuery. Devi specificare l'URL e il nome_funzione che vuoi chiamare.

    $("btn").click(function() {
      $.ajax({url: "demo_test.txt", success: function_name(result) {
        $("#innerdiv").html(result);
      }});
    }); 
    
function get(path) {
    var form = document.createElement("form");
    form.setAttribute("method", "get");
    form.setAttribute("action", path);
    document.body.appendChild(form);
    form.submit();
}


get('/my/url/')

La stessa cosa può essere fatta anche per la richiesta post.
Dai un'occhiata a questo link Richiesta post JavaScript come invio modulo

Per fare questo Fetch API è l'approccio consigliato, usando JavaScript Promises. XMLHttpRequest (XHR), oggetto IFrame o tag dinamici sono approcci più vecchi (e più clunkier).

<script type=“text/javascript”> 
    // Create request object 
    var request = new Request('https://example.com/api/...', 
         { method: 'POST', 
           body: {'name': 'Klaus'}, 
           headers: new Headers({ 'Content-Type': 'application/json' }) 
         });
    // Now use it! 

   fetch(request) 
   .then(resp => { 
         // handle response }) 
   .catch(err => { 
         // handle errors 
    }); </script>

Ecco un ottimo fetch demo e documenti MDN

Richiesta asincrona semplice:

function get(url, callback) {
  var getRequest = new XMLHttpRequest();

  getRequest.open("get", url, true);

  getRequest.addEventListener("readystatechange", function() {
    if (getRequest.readyState === 4 && getRequest.status === 200) {
      callback(getRequest.responseText);
    }
  });

  getRequest.send();
}

Ajax

Sarebbe meglio usare una libreria come Prototype o jQuery .

Se si desidera utilizzare il codice per un widget Dashboard e non si desidera includere una libreria JavaScript in ogni widget creato, è possibile utilizzare l'oggetto XMLHttpRequest che Safari supporta in modo nativo.

Come riportato da Andrew Hedges, un widget non ha accesso a una rete, per impostazione predefinita; devi modificare tale impostazione nella info.plist associata al widget.

Per aggiornare la migliore risposta di joann con promessa questo è il mio codice:

let httpRequestAsync = (method, url) => {
    return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open(method, url);
        xhr.onload = function () {
            if (xhr.status == 200) {
                resolve(xhr.responseText);
            }
            else {
                reject(new Error(xhr.responseText));
            }
        };
        xhr.send();
    });
}

Puoi farlo anche con JS puro:

// Create the XHR object.
function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}

// Make the actual CORS request.
function makeCorsRequest() {
 // This is a sample server that supports CORS.
 var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html';

var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}

// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
alert('Response from CORS request to ' + url + ': ' + text);
};

xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};

xhr.send();
}

Vedi: per maggiori dettagli: html5rocks tutorial

Ecco un'alternativa ai file xml per caricare i tuoi file come oggetto e accedere alle proprietà come oggetto in modo molto veloce.

  • Attenzione, affinché javascript possa farlo e interpretare correttamente il contenuto è necessario salvare i file nello stesso formato della pagina HTML. Se usi UTF 8, salva i tuoi file in UTF8, ecc.

XML funziona come un albero ok? invece di scrivere

     <property> value <property> 

scrivi un file semplice come questo:

      Property1: value
      Property2: value
      etc.

Salva il tuo file .. Ora chiama la funzione ....

    var objectfile = {};

function getfilecontent(url){
    var cli = new XMLHttpRequest();

    cli.onload = function(){
         if((this.status == 200 || this.status == 0) && this.responseText != null) {
        var r = this.responseText;
        var b=(r.indexOf('\n')?'\n':r.indexOf('\r')?'\r':'');
        if(b.length){
        if(b=='\n'){var j=r.toString().replace(/\r/gi,'');}else{var j=r.toString().replace(/\n/gi,'');}
        r=j.split(b);
        r=r.filter(function(val){if( val == '' || val == NaN || val == undefined || val == null ){return false;}return true;});
        r = r.map(f => f.trim());
        }
        if(r.length > 0){
            for(var i=0; i<r.length; i++){
                var m = r[i].split(':');
                if(m.length>1){
                        var mname = m[0];
                        var n = m.shift();
                        var ivalue = m.join(':');
                        objectfile[mname]=ivalue;
                }
            }
        }
        }
    }
cli.open("GET", url);
cli.send();
}

ora puoi ottenere i tuoi valori in modo efficiente.

getfilecontent('mesite.com/mefile.txt');

window.onload = function(){

if(objectfile !== null){
alert (objectfile.property1.value);
}
}

È solo un piccolo dono da contribuire al gruppo. Grazie del tuo like :)

Se vuoi testare la funzione sul tuo PC localmente, riavvia il browser con il seguente comando (supportato da tutti i browser tranne Safari):

yournavigator.exe '' --allow-file-access-from-files
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top