Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
645 views
in Technique[技术] by (71.8m points)

ajax - Jquery ajaxStart doesnt get triggered

This code

$("#loading").ajaxStart(function() {
        alert("start");
        $(this).show();
    });

in my mark-up

<div style="text-align:center;"><img id="loading" src="../images/common/loading.gif" alt="" /></div>

Here is the full ajax request:

$.ajax({
        type: "POST",       

        url: "http://localhost/WebServices/Service.asmx/GetResults",

        data: jsonText,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {

            var results = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
            PopulateTree(results);
        },

        error: function(xhr, status, error) {
            var msg = JSON.parse(xhr.responseText);
            alert(msg.Message);


        }
    });

$("#loading").ajaxStart(function() {
        alert("start");
        $(this).show();
    });

    $("#loading").ajaxStop(function() {
        alert("stop");
        $(this).hide();
        $("#st-tree-container").show();

    });

never fires alert "start" even though the gif is shown to rotate. AjaxStop gets triggered as expected. Any ideas why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's not getting triggered because your handler for .ajaxStart() isn't registered until after the ajax request is already going (past when it would have been called). The .ajaxStop() is registered after as well, but before the request finishes, so when it comes back it is hooked up to run.

To fix this, move this before your first $.ajax() call:

$("#loading").ajaxStart(function() {
  $(this).show();
}).ajaxStop(function() {
  $(this).hide();
  $("#st-tree-container").show();
});


UPDATE: Starting jQuery 1.9, AJAX events should be attached to document only. http://jquery.com/upgrade-guide/1.9/#ajax-events-should-be-attached-to-document

$(document).ajaxStart(function() {
  $("#loading").show();
});

$(document).ajaxStop(function() {
  $("#loading").hide();
  $("#st-tree-container").show();
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...