$。当()。然后,()不工作嵌套Ajax调用 [英] $.when().then() not working with nested ajax calls

查看:121
本文介绍了$。当()。然后,()不工作嵌套Ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图将页面滚动到一个动态 DIV 是由Ajax调用创建。

#divnotifications DIV 点击(如下图),我做的第一个Ajax调用,增加了发表详细信息,那么这个Ajax调用中,另一个AJAX调用了相关的注释添加到div。

部分解释目前的伟大工程。然后,我用 $。当()。则()滚动到一个div项目​​创建基于Ajax调用。但是,页面不滚动到由 LoadCommentsForPost Ajax调用创建的元素。

我才拿到 $的逻辑。当()。那么()错了吗?

  $(文件)。在('点击','#divnotifications格',函数(事件){
          。事件preventDefault();
          $阿贾克斯({
              //其他细节
              成功:函数(postid){
                  $。当(DisplayPostWithFullDetails(postid))。然后(函数(){
                      //滚动到所创造的内容
                      // LoadCommentsForPost函数嵌套
                      //里面DisplayPostWithFullDetails
                  });
              }
          });
    });

    功能DisplayPostWithFullDetails(postId){
         $阿贾克斯({
            //其他细节
            成功:函数(后){
                //将code建div来显示文章 - 做工精细
                LoadCommentsForPost(post.PostId);

            }
        });
    }

    功能LoadCommentsForPost(postid){
        $阿贾克斯({
            //其他细节
            成功:函数(响应){
                变种注释= JSON.parse(响应);
                DisplayComments(意见); //构建div来显示的评论 - 做工精细
            }
        });
    }
 

修订code

收到一些反馈后,我结束了以下code。然而,它仍不能工作。它只有当我添加一些延迟,以确保分区加载:

  $(文件)。在('点击','#divnotifications格',函数(事件){
        。事件preventDefault();
        $阿贾克斯({
            //其他Ajax东西
             成功:函数(postid){
                  DisplayPostWithFullDetails(postid).done(函数(){
                          的setTimeout(函数(){
                              VAR scrollto = $(格[数据 - + type.toLowerCase()+displayform ='+ relateditem +'])的偏移量()顶部。;
                              $(HTML,机构)动画({scrollTop的:scrollto},600);
                          },500);
                  });
             }
        });
    });

    功能DisplayPostWithFullDetails(postId){
        jQuery.support.cors = TRUE;
        返回$阿贾克斯({
            //其他Ajax东西
            成功:函数(后){
                交= JSON.parse(后);
                //显示文章的详细信息

                LoadCommentsForPost(post.PostId);
            }
        });
    }

    功能LoadCommentsForPost(postid){
        VAR诺=新的$ .Deferred();
        jQuery.support.cors = TRUE;
        $阿贾克斯({
            //其他Ajax东西
            成功:函数(响应){
                变种注释= JSON.parse(响应);
                DisplayComments(意见); //这不是阿贾克斯

                promise.resolve('loadedcomments');
            }
        });

        返回的承诺;
    }
 

解决方案
  

我是否得到$。当()的逻辑则()错了?

没有,但你没有返回的承诺,所以你不能使用类似。然后承诺函数()。

更新:

  

我用$。当()。然后,()滚动到一个div项目​​基于Ajax调用创建的。但是,页面不滚动到被LoadCommentsForPost Ajax调用创建的元素。

对于我来说,这意味着你需要等待两个Ajax调用解决了。

这小提琴表演应该是如何工作的模拟Ajax调用使用setTimeout的小提琴

您code可能类似于:

 函数DisplayPostWithFullDetails(postId){
   VAR诺=新的$ .Deferred();
   $阿贾克斯({
       //其他细节
        成功:函数(后){
           //将code建div来显示文章 - 做工精细
           LoadCommentsForPost(post.PostId)。然后(函数(){
               promise.resolve();
           });

        }
    });
    返回的承诺;
}

功能LoadCommentsForPost(postid){
    返回$阿贾克斯({
        //其他细节
        成功:函数(响应){
            变种注释= JSON.parse(响应);
            DisplayComments(意见); //构建div来显示的评论 - 做工精细
        }
    });
}
 

现在,当您执行函数DisplayPostWithFullDetails它返回一个承诺。 所以,你可以使用。那么()方法;

  DisplayPostWithFullDetails(postid)),然后(函数(){})。
 

  VAR承诺= DisplayPostWithFullDetails(postid);
promise.then(功能(数据){});
 

此外使用$。当主要优点()是可以执行的。那么()方法时,所有你传递给它的承诺都解决了。

有不需要使用它时,你正在等待一个承诺。

I have been trying to scroll the page to a dynamic div that is created by the an ajax call.

When #divnotifications div clicked (below), I make the first ajax call that adds the Post details, then within this ajax call, another ajax call is made to add the related comments to the div.

The part explained so far works great. Then, I use $.when().then() to scroll to a div item created based on the ajax calls. However, the page does not scroll to the element that was created by LoadCommentsForPost ajax call.

Did I get the logic of $.when().then() wrong?

    $(document).on('click', '#divnotifications div', function (event) {
          event.preventDefault();
          $.ajax({
              //other details
              success: function (postid) {
                  $.when(DisplayPostWithFullDetails(postid)).then(function () {                            
                      //scroll to the content created by 
                      //LoadCommentsForPost function nested 
                      //inside DisplayPostWithFullDetails
                  });
              }
          });                
    });

    function DisplayPostWithFullDetails(postId) {
         $.ajax({
            //other details
            success: function (post) {
                //The code to build the div to display the post -- working fine
                LoadCommentsForPost(post.PostId);                

            }
        });
    }

    function LoadCommentsForPost(postid) {
        $.ajax({
            //other details
            success: function (response) {
                var comments = JSON.parse(response);
                DisplayComments(comments);//builds the div to display the comments - working fine
            }
        });
    }

UPDATED CODE

After receiving some feedback, I ended up with the following code. However, it is still not working. It works only if I add some delay to make sure the div is loaded:

    $(document).on('click', '#divnotifications div', function (event) {
        event.preventDefault();
        $.ajax({
            //other ajax stuff
             success: function (postid) {
                  DisplayPostWithFullDetails(postid).done(function () {
                          setTimeout(function () {
                              var scrollto = $("div[data-" + type.toLowerCase() +  "displayform='" + relateditem + "']").offset().top;
                              $("html, body").animate({ scrollTop: scrollto }, 600);
                          }, 500);
                  });
             }
        });
    });

    function DisplayPostWithFullDetails(postId) {
        jQuery.support.cors = true;
        return $.ajax({
            //other ajax stuff
            success: function (post) {
                post = JSON.parse(post);
                //display the post details

                LoadCommentsForPost(post.PostId);
            }
        });
    }

    function LoadCommentsForPost(postid) {
        var promise = new $.Deferred();
        jQuery.support.cors = true;
        $.ajax({
            //other ajax stuff
            success: function (response) {
                var comments = JSON.parse(response);
                DisplayComments(comments);//this is not ajax 

                promise.resolve('loadedcomments');
            }
        });

        return promise;
    }

解决方案

Did I get the logic of $.when().then() wrong?

No, but you are NOT returning the promise so you can't use the promise functions like .then().

UPDATE:

I use $.when().then() to scroll to a div item created based on the ajax calls. However, the page does not scroll to the element that was created by LoadCommentsForPost ajax call.

For me this means that you need to wait that both ajax calls are resolved.

This fiddle show how it should work emulating the ajax call using setTimeout Fiddle.

Your code may look similar to:

function DisplayPostWithFullDetails(postId) {
   var promise = new $.Deferred();
   $.ajax({
       //other details
        success: function (post) {
           //The code to build the div to display the post -- working fine
           LoadCommentsForPost(post.PostId).then(function() {
               promise.resolve();
           });                

        }
    });
    return promise;
}

function LoadCommentsForPost(postid) {
    return $.ajax({
        //other details
        success: function (response) {
            var comments = JSON.parse(response);
            DisplayComments(comments);//builds the div to display the comments - working fine
        }
    });
}

Now when you execute the function DisplayPostWithFullDetails it return a promise. So you can use .then() method;

DisplayPostWithFullDetails(postid)).then(function () {});

or...

var promise = DisplayPostWithFullDetails(postid);
promise.then(function(data){});

Also the major advantage of use $.when() is that you can execute the .then() method when all the promises that you pass to it are resolved.

There are not need to use it when you are waiting for a single promise.

这篇关于$。当()。然后,()不工作嵌套Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆