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

196
Visualizações
Javascript use fetch to get html response

I'm currently using ajax in a javascript file to get a response which is just some HTML.

My ajax script looks like :

$.ajax({
                    type: $form.getAttribute('action'),
                    method: $form.getAttribute('method'),
                    url: '{{ url|raw }}',
                    data: data,
                    success: function (html) {
                        html = new DOMParser().parseFromString(html, "text/html");
                        document.querySelector('#S3Adapter_storageClass').parentElement.replaceWith(html.querySelector('#S3Adapter_storageClass').parentElement);
                    }
                });

Basically it makes an ajax request to my controller which will return HTML content to me, in which I will just take a part to replace the current content of my page.

This works fine, but I'd like to skip jQuery and therefore use fetch() instead.

Except I can't. While searching the internet, I found on this site a way to do it: https://gomakethings.com/getting-html-with-fetch-in-vanilla-js/

So I did :

fetch('{{ url|raw }}', {
                    method: $form.getAttribute('method'),
                    body: data,
                }).then(function (response) {
                    // The API call was successful!
                    return response.text();
                }).then(function (html) {
                    // This is the HTML from our response as a text string
                    html = new DOMParser().parseFromString(html, "text/html");
                    document.querySelector('#S3Adapter_storageClass').parentElement.replaceWith(html.querySelector('#S3Adapter_storageClass').parentElement);
                }).catch(function (err) {
                    // There was an error
                    console.warn('Something went wrong.', err);
                });

Eventually, I do get some HTML content, but I feel like it's not the one that should be returned by the response like I did in Ajax. Instead, I just get the HTML of my current page. Is there something I did wrong?

about 4 years ago · Juan Pablo Isaza
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