jQuery 嵌套 Ajax 调用不起作用

发布于 2024-11-02 16:54:07 字数 1779 浏览 5 评论 0原文

我正在尝试进行嵌套 ajax 调用,但迭代不起作用:假设我有 2 家公司,其中公司号 1 有 2 个联系人,公司号 2 有 3 个联系人。我不明白为什么,但下面给出的代码显示两个公司名称,后跟五个联系人姓名:它不是嵌套的......

    <script type="text/javascript">
    $(function () {
        $('#searchbutton').bind('click', function (event) {
            $("#result > h4, #result > p").remove();
            $("<p>Loading...</p>").appendTo($("#result"));
            $.ajax({
                type: "GET",
                dataType: "jsonp",
                cache: true,
                url: "http://localhost/archilab/archilabdirectory.svc/",
                data: ("tag=" + $("#searchstring").val()),
                success: function (companies) {
                    $("#result > p").remove();
                    $.each(companies, function () {
                        var outer = this;
                        $("<h4>", { text: outer.Name + " (" + outer.Perimeter + ")" }).hide().appendTo($("#result")).show(4000, function () {
                            $.ajax({
                                type: "GET",
                                dataType: "jsonp",
                                cache: true,
                                url: "http://localhost/archilab/archilabdirectory.svc/" + outer.Name + "/contacts/",
                                success: function (contacts) {
                                    $(contacts).each(function () {
                                        $("<p>", { text: this.FirstName + " " + this.LastName }).hide().appendTo($("#result")).show();
                                    });
                                }
                            })
                        });
                    });
                }
            });
        })
    });
</script>

I'm trying to make nested ajax calls but the iteration does not work : let's say i have 2 companies with company number 1 having 2 contacts and company number 2 having 3 contacts. I Can't figure out why but the code given below displays the two company names followed by the five contact names : it is not nested....

    <script type="text/javascript">
    $(function () {
        $('#searchbutton').bind('click', function (event) {
            $("#result > h4, #result > p").remove();
            $("<p>Loading...</p>").appendTo($("#result"));
            $.ajax({
                type: "GET",
                dataType: "jsonp",
                cache: true,
                url: "http://localhost/archilab/archilabdirectory.svc/",
                data: ("tag=" + $("#searchstring").val()),
                success: function (companies) {
                    $("#result > p").remove();
                    $.each(companies, function () {
                        var outer = this;
                        $("<h4>", { text: outer.Name + " (" + outer.Perimeter + ")" }).hide().appendTo($("#result")).show(4000, function () {
                            $.ajax({
                                type: "GET",
                                dataType: "jsonp",
                                cache: true,
                                url: "http://localhost/archilab/archilabdirectory.svc/" + outer.Name + "/contacts/",
                                success: function (contacts) {
                                    $(contacts).each(function () {
                                        $("<p>", { text: this.FirstName + " " + this.LastName }).hide().appendTo($("#result")).show();
                                    });
                                }
                            })
                        });
                    });
                }
            });
        })
    });
</script>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怪我鬧 2024-11-09 16:54:07

您确实意识到您的 $.ajax 调用是异步的,对吧?此 each

$.each(companies, function () { /* ... */ });

将添加一个

,启动异步 $.ajax 调用,然后重复 中的下一个条目>公司。 AJAX 调用几乎肯定比 $.each 需要更长的时间才能完成,因此它将生成公司名称

,然后 AJAX 调用将完成并且添加

。甚至无法保证

将以正确的顺序添加。

如果您需要事情按特定顺序发生,那么您将必须添加 async: false 到您的 $.ajax 调用。

更新:我需要比评论提供的空间多一点的空间。不,这不是我的最后一个定理。

您可以将

内容推送到内部成功处理程序中,但这仍然会让您面临排序问题(即第二个 AJAX 调用可能会在第一个 AJAX 调用之前完成)。我认为最简单的方法是在

周围添加带有 ID 属性的包装器

code> 元素,这将为您提供 .append 调用的简单目标;有点像这样:

$.each(companies, function() {
    var $wrapper_hack = $('<div/>');
    $('#result').append($wrapper_hack);
    add_content($wrapper_hack, outer);
});

// And elsewhere...
function add_content($wrapper_hack, outer) {
    $("<h4>", {
        text: outer.Name + " (" + outer.Perimeter + ")"
    }).hide().appendTo($wrapper_hack).show(4000, function () {
        $.ajax({
            /* ... */
            success: function(contacts) {
                /* Build your <p> and append it to $wrapper_hack */
            }
        });
    });
}

这个想法是将内容附加到仅附加到右侧

的内容,而不是附加到 #result;然后,所有内容都会以正确的顺序出现,因为您已在 HTML 元素嵌套中嵌入了正确的顺序。您需要将 add_content 作为单独的函数来正确地将 $wrapper_hackouter 本地化为所需的上下文,从而避免常见的关闭问题。

You do realize that your $.ajax calls are asynchronous, right? This each:

$.each(companies, function () { /* ... */ });

Will add an <h4>, launch an asynchronous $.ajax call, and then repeat for the next entry in companies. The AJAX calls will almost certainly take longer to finish than the $.each so it will produce the company name <h4>s and then the AJAX calls will finish up and add the <p>s. There is no guarantee that the <p>s will even be added in the right order.

If you need things to happen in a specific order then you're going to have to add async: false to your $.ajax calls.

UPDATE: I need a bit more space than a comment provides. No, this is not my last theorem.

You could push the <h4> stuff down into the inner success handler but this would still leave you open to ordering issues (i.e. the second AJAX call could complete before the first). I think the easiest thing to do would be to add wrapper <div>s with ID attributes around your <h4> and <p> elements, this would give you an easy target for a .append call; something sort of like this:

$.each(companies, function() {
    var $wrapper_hack = $('<div/>');
    $('#result').append($wrapper_hack);
    add_content($wrapper_hack, outer);
});

// And elsewhere...
function add_content($wrapper_hack, outer) {
    $("<h4>", {
        text: outer.Name + " (" + outer.Perimeter + ")"
    }).hide().appendTo($wrapper_hack).show(4000, function () {
        $.ajax({
            /* ... */
            success: function(contacts) {
                /* Build your <p> and append it to $wrapper_hack */
            }
        });
    });
}

The idea is to append content to something attached just to the right <h4> rather than appending to #result; then, everything will appear in the right order because you have embedded the correct order in your the HTML element nesting. You'll need add_content as a separate function to properly localize $wrapper_hack and outer to just the desired context and thus avoid the usual closure problems.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文