How to call second jQuery.ajax instance on success of first and update page

后端 未结 2 1916
梦毁少年i
梦毁少年i 2020-12-31 07:43

I have some jQuery that is triggered on click of a link with the class \'changetag\'. I\'m using $.ajax() to update the database via changetag.php.

相关标签:
2条回答
  • 2020-12-31 08:33

    Ajax calls are (by default) asynchronous. That means that this code:

    $("#li_"+I).toggleClass("off on");
    element.toggleClass("off on");
    
    return false;
    

    could be executed before the ajax call preceding it is finished. This is a common problem for programmers who are new to ajax and asynchronous code execution. Anything you want to be executed after the ajax call is done must be put into a callback, such as your success handler:

    $.ajax({
        type: "POST",
        url: "_js/changetag.php",
        data: info,
        success: function(){
            $("#li_"+I).toggleClass("off on");
            element.toggleClass("off on");
        }
    });
    

    Likewise, you could put the second ajax call in there as well:

    $.ajax({
        type: "POST",
        url: "_js/changetag.php",
        data: info,
        success: function(){
            $("#li_"+I).toggleClass("off on");
            element.toggleClass("off on");
    
            $.ajax({
                url: "_js/loaddeals_v2.php",
                success: function(results){
                    $('#listresults').empty();
                    $('#listresults').append(results);
                }
            });
        }
    });
    

    With jQuery 1.5's Deferred Object, you can make this slicker.

    function firstAjax() {
        return $.ajax({
            type: "POST",
            url: "_js/changetag.php",
            data: info,
            success: function(){
                $("#li_"+I).toggleClass("off on");
                element.toggleClass("off on");
            }
        });
    }
    
    // you can simplify this second call and just use $.get()
    function secondAjax() {
        return $.get("_js/loaddata.php", function(results){
            $('#listresults').html(results);
        });
    }
    
    // do the actual ajax calls
    firstAjax().success(secondAjax);
    

    This is nice because it lets you un-nest callbacks - you can write code that executes asynchronously, but is written like synchronously-executed code.

    0 讨论(0)
  • 2020-12-31 08:43

    Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead. https://api.jquery.com/jQuery.ajax/#jqXHR

    0 讨论(0)
提交回复
热议问题