Pergunta

Eu preciso fazer um Http get solicitação em javascript. Qual é a melhor maneira de fazer isso?

Eu preciso fazer isso em um widget Mac OS X DashCode.

Foi útil?

Solução

Os navegadores (e o código de painel) fornecem um objeto xmlHttPrequest que pode ser usado para fazer solicitações HTTP do JavaScript:

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

No entanto, os pedidos síncronos são desencorajados e gerarão um aviso ao longo das linhas de:

Nota: Começando com Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / Seamonkey 2.27), pedidos síncronos no fio principal foram preteridos Devido aos efeitos negativos à experiência do usuário.

Você deve fazer uma solicitação assíncrona e lidar com a resposta dentro de um manipulador de eventos.

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

Outras dicas

Em jQuery:

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

Muitos ótimos conselhos acima, mas não são muito reutilizáveis, e muitas vezes cheios de bobagens de dom e outras cotades que ocultam o código fácil.

Aqui está uma classe JavaScript que criamos que é reutilizável e fácil de usar. Atualmente, ele tem apenas um método GET, mas isso funciona para nós. Adicionar uma postagem não deve tributar as habilidades de ninguém.

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

Usá -lo é tão fácil quanto:

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

Uma versão sem retorno de chamada

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

O novo window.fetch API é um substituto mais limpo para XMLHttpRequest Isso faz uso de promessas do ES6. Há uma boa explicação aqui, mas tudo se resume a (do artigo):

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

Suporte ao navegador Agora é bom nos lançamentos mais recentes (trabalhos em Chrome, Firefox, Edge (V14), Safari (V10.1), Opera, Safari iOS (V10.3), Android Browser e Chrome para Android), no entanto, o IE provavelmente não será Obtenha apoio oficial. Github tem um poli -preenchimento Disponível, recomendado para apoiar os navegadores mais antigos ainda em uso (versões ESP do Safari antes de março de 2017 e navegadores móveis do mesmo período).

Eu acho que isso é mais conveniente do que o jQuery ou o XmlHttPrequest ou não depende da natureza do projeto.

Aqui está um link para a especificação https://fetch.spec.whatwg.org/

Editar:

Usando o ES7 Async/Await, isso se torna simplesmente (com base em esta essência):

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

Aqui está o código para fazê -lo diretamente com o JavaScript. Mas, como mencionado anteriormente, você estaria muito melhor com uma biblioteca JavaScript. Meu favorito é jQuery.

No caso abaixo, uma página ASPX (que está atendendo como serviço de repouso de um homem pobre) está sendo chamado para devolver um objeto JavaScript JSON.

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;
        }                    
    }
}

Uma versão pronta para colo de cópia

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

O IE irá cache os URLs para tornar o carregamento mais rápido, mas se você estiver, digamos, pesquisar um servidor em intervalos que tentam obter novas informações, ou seja, cache esse URL e provavelmente retornará o mesmo conjunto de dados que você sempre teve.

Independentemente de como você acaba fazendo sua solicitação GE - Javascript de baunilha, protótipo, jQuery, etc. - certifique -se de colocar um mecanismo no lugar para combater o cache. Para combater isso, anexar um token exclusivo ao final do URL, você estará batendo. Isso pode ser feito por:

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

Isso anexará um registro de data e hora exclusivo ao final do URL e impedirá que qualquer cache aconteça.

Curto e puro:

const http = new XMLHttpRequest()

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

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

Protótipo simplifica

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

Não estou familiarizado com os widgets do Mac OS Dashcode, mas se eles permitirem que você use bibliotecas e suporte JavaScript XmlHttPrequests, Eu usaria jQuery E faça algo assim:

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

Uma solução que suporta navegadores mais antigos:

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

Talvez um pouco exagerado, mas você definitivamente fica seguro com este código.

Uso:

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

No arquivo info.plist do seu widget, não se esqueça de definir seu AllowNetworkAccess Chave para True.

A melhor maneira é usar o Ajax (você pode encontrar um tutorial simples nesta página Tizag). O motivo é que qualquer outra técnica que você possa usar requer mais código, não é garantido que trabalhe o navegador cruzado sem retrabalho e exige que você use mais memória do cliente, abrindo as páginas ocultas dentro dos quadros que passam os URLs analisando seus dados e fechando -os. Ajax é o caminho a seguir nessa situação. Que meus dois anos de desenvolvimento de desenvolvimento pesado de JavaScript.

Para quem usa AngularJS, Está $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.
  });

Você pode obter uma solicitação HTTP de duas maneiras:

  1. Essa abordagem baseada no formato XML. Você tem que passar no URL para o pedido.

    xmlhttp.open("GET","URL",true);
    xmlhttp.send();
    
  2. Este é baseado no jQuery. Você deve especificar o URL e o Function_Name que deseja ligar.

    $("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/')

A mesma coisa também pode ser feita para solicitação de postagem.
dê uma olhada neste link Solicitação de postagem de javascript como um formulário Enviar

Para fazer isso, a API busca é a abordagem recomendada, usando promessas de JavaScript. Xmlhttprequest (xhr), objeto iframe ou tags dinâmicas são abordagens mais antigas (e mais clunks).

<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>

Aqui está um ótimo Fetch Demo e Mdn Docs

Solicitação assíncrona simples:

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

Você seria melhor usar uma biblioteca como Protótipo ou jQuery.

Se você deseja usar o código para um widget de painel e não deseja incluir uma biblioteca JavaScript em todos os widgets que você criou, você pode usar o objeto XMLHTTPRequest que o Safari suporta nativamente.

Conforme relatado por Andrew Hedges, um widget não tem acesso a uma rede, por padrão; Você precisa alterar essa configuração na info.plist associada ao widget.

Para atualizar a melhor resposta de JoAnn com promessa, este é o meu código:

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

Você pode fazer isso com JS puro também:

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

Veja: Para mais detalhes: Tutorial HTML5ROCKS

Aqui está uma alternativa aos arquivos XML para carregar seus arquivos como um objeto e acessar as propriedades como um objeto de maneira muito rápida.

  • Atenção, para que o JavaScript possa ele e interpretar o conteúdo corretamente, é necessário salvar seus arquivos no mesmo formato que sua página HTML. Se você usar o UTF 8, salve seus arquivos no UTF8, etc.

XML funciona como uma árvore ok? em vez de escrever

     <property> value <property> 

Escreva um arquivo simples como este:

      Property1: value
      Property2: value
      etc.

Salve seu arquivo .. agora ligue para a função ....

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

Agora você pode obter seus valores com eficiência.

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

window.onload = function(){

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

É apenas um pequeno presente para contribuir para o grupo. Obrigado do seu lado :)

Se você deseja testar a função no seu PC localmente, reinicie o navegador com o seguinte comando (suportado por todos os navegadores, exceto Safari):

yournavigator.exe '' --allow-file-access-from-files
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top