2017-03-18 5 views
0

Ich möchte Loader in meiner Website hinzufügen, und ich verwende AjaxStart und AjxStop Anfrage zum Ausblenden und Anzeigen div. aber das Problem ist ajaxStart und AjaxStop Anfrage wird nicht ausgelöst durch Knopf onclick. Unten ist mein Code:ajaxStart funktioniert nicht auf onclick

<style> 
    //css for loader 
    //another class with overflow=hidden 
</style> 

jetzt, was ich tun möchte, ist:

$("#msg1").click(function(event){   //msg1 is the id of the button 
    $body = $("body"); 
    $.ajaxSetup({'global':true}); 
    $(document).ajaxStart(function(){ 
     $body.addClass("loading"); 
    }); 
    }); 

aber das funktioniert nicht. unter Code funktioniert:

$("#msg1").click(function(event){   //msg1 is the id of the button 
    alert("Hello"); 
}); 

Also, wo fehlt mir der Punkt?

Antwort

1

ajaxStart registriert einen Handler für immer, wenn eine Ajax-Anfrage beginnt, es feuert tatsächlich keinen Ajax-Anruf. Mit dem, was Sie geschrieben haben, wird die "loading" -Klasse zum Body-Tag hinzugefügt, wenn Sie jetzt eine der jQuery-Methoden verwenden, um einen Ajax-Aufruf durchzuführen.

z.B.

$(".result").load("ajax/test.html"); 

UPDATE

so zu etwas ändern Sie den Code, um es

// Move these out of the click handler as they don't have to run every time 
// the button is clicked. 
var $body = $("body"); 

$.ajaxSetup({'global':true}); 

$(document).ajaxStart(function(){ 
    $body.addClass("loading"); 
}); 

$("#msg1").click(function(event){ 
    // Here is where you actually make the ajax call, so the "loading" class 
    // will now be added to the body tag. 
    $.ajax("example.php") 
     .done(function(data) { 
     // Do something with the data you've just retrieved. 
     // You probably now want to remove the "loading" class too. 
    }) 
}); 
+0

zu machen arbeite ich genau das tun wollen. Ich möchte mit ajaxStart die Klasse "loading" zum Körper hinzufügen. –

+0

aber ich weiß nicht, warum ajaxStart nicht ausgelöst wird –

+0

Weil du noch keinen Ajax-Anruf getätigt hast, hast du nur gesagt: "Wenn ich einen Ajax-Anruf tätige, füge dem Körper die Klasse 'loading' hinzu" . Du musst den Ajax noch selbst anrufen, macht das Sinn? – Chris