how to wait for an ajax call to return

前端 未结 6 842
天涯浪人
天涯浪人 2021-01-12 20:00

I\'m trying to use JQuery although i\'m struggling to successfully wait for a ajax call to succeed before executing further code. Is there a way to wait for an ajax to call

6条回答
  •  一向
    一向 (楼主)
    2021-01-12 21:00

    You can use success or complete callbacks. Success fires if the server returns a 200. Complete will fire when the request is finished, regardless of the response status.

    $.ajax({
        url: "/path/to/action",
        success: function() {
            alert("do something if it's successful");
        },
        complete: function(request, status) {
            alert("do something when it's finished, regardless of success.");
        }
    });
    

    or you can do a synchronous call:

    $.ajax({
        url: "/path/to/action",
        async: false
    });
    

提交回复
热议问题