¿Cómo sé si jQuery tiene una solicitud Ajax pendiente?


Estoy teniendo algunos problemas con un control de jQuery que hicimos. Supongamos que tiene una lista desplegable que le permite ingresar el ID del elemento que está buscando, y cuando presiona ENTER o pierde el foco en un cuadro de texto, valida a través de jQuery que el ID que ingresó es correcto, mostrando una alerta si no lo hace.

La cosa es que cuando un usuario ordinario ingresa un valor no válido en él y pierde el foco presionando el botón enviar, el mensaje de jQuery regresa después de que el envío del formulario haya sido enviado.

¿Hay alguna forma de que pueda verificar si hay algún procesamiento de solicitudes Asincrónicas por parte de jQuery para que no permita el envío del formulario?

Author: skaffman, 2009-12-01

5 answers

Puede usar ajaxStart y ajaxStop para realizar un seguimiento de cuándo están activas las solicitudes.

 33
Author: ceejayoz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-30 23:05:31

$.active devuelve el número de solicitudes Ajax activas.

Más información aquí

 202
Author: sivabudh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:55:00
 $(function () {
        function checkPendingRequest() {
            if ($.active > 0) {
                window.setTimeout(checkPendingRequest, 1000);
                //Mostrar peticiones pendientes ejemplo: $("#control").val("Peticiones pendientes" + $.active);
            }
            else {

                alert("No hay peticiones pendientes");

            }
        };

        window.setTimeout(checkPendingRequest, 1000);
 });
 24
Author: etgregor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-25 17:42:43

El $.la función ajax () devuelve un objeto XMLHttpRequest. Almacene eso en una variable que sea accesible desde el evento "OnClick" del botón Enviar. Cuando se procesa un clic de envío, compruebe si la variable XMLHttpRequest es:

1) null, lo que significa que aún no se ha enviado ninguna solicitud

2) que el valor readyState es 4 (Loaded). Esto significa que la solicitud se ha enviado y devuelto con éxito.

En cualquiera de esos casos, devuelve true y permite que el envío continúe. De lo contrario, devuelve false para bloquear el envío y dar al usuario alguna indicación de por qué su envío no funcionó. :)

 10
Author: Toji,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-30 23:08:37

Tenemos que utilizar $.ajax.abort () método para abortar la solicitud si la solicitud está activa. Este objeto promise utiliza la propiedad readyState para comprobar si la solicitud está activa o no.

HTML

<h3>Cancel Ajax Request on Demand</h3>
<div id="test"></div>
<input type="button" id="btnCancel" value="Click to Cancel the Ajax Request" />

Código JS

//Initial Message
var ajaxRequestVariable;
$("#test").html("Please wait while request is being processed..");

//Event handler for Cancel Button
$("#btnCancel").on("click", function(){
if (ajaxRequestVariable !== undefined)

if (ajaxRequestVariable.readyState > 0 && ajaxRequestVariable.readyState < 4)
{
  ajaxRequestVariable.abort();
  $("#test").html("Ajax Request Cancelled.");
}
});

//Ajax Process Starts
ajaxRequestVariable = $.ajax({
            method: "POST",
            url: '/echo/json/',
            contentType: "application/json",
            cache: false,
            dataType: "json",
            data: {
        json: JSON.encode({
         data:
             [
                            {"prop1":"prop1Value"},
                    {"prop1":"prop2Value"}
                  ]         
        }),
        delay: 11
    },

            success: function (response) {
            $("#test").show();
            $("#test").html("Request is completed");           
            },
            error: function (error) {

            },
            complete: function () {

            }
        });
 1
Author: vibs2006,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-02 05:02:57