Ajax调用完成后如何执行函数

PVB*_*aju 2 html javascript css jquery liferay

我有两个函数,第一个函数有 ajax 调用,所以我希望在 ajax 调用(这里我正在重新加载页面)完成后执行第二个函数,你能帮我吗?
这里是下面的代码

<div id="exapnd_or_collapse_div" class="exapnd_or_collapse_div" onclick="changeLayout();">
<script>
function changeLayout () {
    alert('change layout');

    try {
        jQuery.ajax({
            url:'<%=resourceURL.toString()%>',
            dataType: "text",
            data:{
                <portlet:namespace  />cmd:'changeLayout'
            },
            error: function(){
             alert("AJAXError");
            },
            type: "post",

            success: function(data) {

                if("success" == data) {

                    location.reload();
                }
            }
        }).done(function(){
            exapndCollapse(); 
          });


    } catch(e) {
        alert('waiting: ' + e);
    }
};

function expandCollapse() {


            jQuery("div.Search_Styled-dropDown").css("display", "none");
            jQuery("span.menu-text").css("display", "none");

            jQuery("ul.Common_ul").css("display", "none");
            jQuery("img.module_images").css("width", "25px");
            jQuery("img.module_images").css("margin-top", "20px");
        jQuery("img.module_images").css("height", "21px");
            jQuery("#search_box").css("display", "none");   
        jQuery("#Escaped_toggle").css("margin-right", "94%");   
        }
</script>
Run Code Online (Sandbox Code Playgroud)

Cha*_*rma 5

如您所知,Ajax 是发出异步请求。这意味着客户端无需等到您从服务器获得响应。所以在这个 Ajax 对象会进入不同的状态即从 0 到 4)。那些是:

  • 0:请求未初始化
  • 1:服务器连接建立
  • 2:收到请求
  • 3:处理请求
  • 4:请求完成,响应准备好

因此,根据您的要求,有两种解决方案:

  • 要么你做同步请求(但不推荐)
  • 当 readystate 值为 4 时,您需要调用第二个函数

参考下面的代码,它会帮助你:

function changeLayout() {
    try{
        jQuery.ajax({
            url:'<%=resourceURL.toString()%>',
            dataType: "text",
            data:{
                <portlet:namespace  />cmd:'changeLayout'
            },
            type: "post",

            beforeSend: function(){
                //before send this method will be called
            },
            success: function(data) {
                //when response recieved then this method will be called.
            }
            complete: function(){
                //after completed request then this method will be called.
            },
            error: function(){
                //when error occurs then this method will be called.
            }
        });
    }catch (e) {
        alert(e);
    }
}
Run Code Online (Sandbox Code Playgroud)

希望能帮到你 :)