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

157
Visualizações
How to handle multiple response types in ajax

Currently, I have a form, submitting which will redirect to an error page or download a file. However, recently server side was modified, and as for now, it could also return some JSON, which I need to handle. Thus, as far as I've got, you can't get a form submission result, I've made a POST call instead of a form, but how could I handle different return types? I ought to use jQuery for it, and currently it works as follows only for downloading:

$.ajax({
            url: 'some-url',
            type: 'POST',
            cache: false,
            data: {
                // some required data
            },
            xhrFields: {
                responseType: 'blob'
            },
            success: function(response, status, req) {
                if (response.hasSuggestions) {
                    // this code is prepared to work with JSON data
                    return;
                }

                var fileName = req.getResponseHeader('content-disposition').split('; ')[1].replace('filename=', '');

                var contentType = req.getResponseHeader('content-type');

                var blob = new Blob([response], { type: contentType });

                var isIE = false || !!document.documentMode;
                if (isIE) {
                    window.navigator.msSaveBlob(blob, fileName);
                } else {
                    var url = window.URL || window.webkitURL;
                    link = url.createObjectURL(blob);
                    var a = $("<a />");
                    a.attr("download", fileName);
                    a.attr("href", link);
                    $("body").append(a);
                    a[0].click();
                    a.remove();
                }
            },
        error: // some error handler
    })

And if server returns JSON data or redirect, I'm just getting "[object Blob]". I know, that it is due to response-type field, but how could I handle different types of response? P.S. If I'll not set a response-type, there will be a huge headache on properly converting string to blob

about 4 years ago · Santiago Gelvez
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