Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda