Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
How to set an image's src from the API response?

I have this code that gets an image from the Minecraft API via uuid or username. It gets the value from an input tag.

HTML:

<input type="text" id="nameinput" placeholder="Username"/>
<img src="" id="display"/>
<script type="text/javascript" src="/JS/login-page.js"></script>

Js:

document.querySelector("#nameinput").oninput = function(){
    var request = new XMLHttpRequest();
    request.onload = function() {
        // Grab data and assing feilds
        var response = JSON.parse(request.responseText);
        var uuid = response.id;
        
        if (typeof(uuid) == "undefined") {
            response.id = "steve";
        }
        
        document.querySelector("#display").src = "https://crafatar.com/avatars/" + uuid + "?overlay&size=512";
    };

    request.open("GET", "https://api.year4000.net/minecraft/" + document.querySelector("#nameinput").value, true);
    request.send();
}

Basically, I want to move the image from the API over to display it in the image tag. How do I do this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I recommend using addEventListener instead of setting the oninput attribute.

const nameInput = document.querySelector("#nameinput");
const img = document.querySelector("#display");

nameInput.addEventListener('input', function () {
    
    // Don't do anything if the value is empty
    if (this.value === '') return;
    
    const request = new XMLHttpRequest();
    request.onload = function () {
        const response = JSON.parse(request.responseText);
        const { id } = response;
        img.setAttribute('src', `https://crafatar.com/avatars/${id}?overlay&size=512`);
    };
    request.open("GET", "https://api.year4000.net/minecraft/" + this.value, true);
    request.send();
});
<input type="text" id="nameinput" placeholder="test123" /><br>
<img id="display" src="" />

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda