jquery - 如何在 '.append()'循环内同步 'for'和ajax查询

标签 jquery ajax wordpress asynchronous

大家好!我似乎遇到了异步操作问题,我不知道如何处理。

我希望显示此代码

Category 1,

Items of category 1

Category 2,

Items of category 2

Category 3,

Items of category 3

我得到的是:

Category 1,

Category 2,

Category 3,

Items of category 1

Items of category 2

Items of category 3

这是代码:

function showSubheadersMenu (items) {
    for (j = 0; j < items.length; j++) {
      $("#gallery").append($("<div id=" + items[j].id + " class=\"gallery-item\"><div class=\"item-img\" style=\"background-image:url(" + items[j].better_featured_image.source_url + ")\"></div></div>"));
    }
  }

 function showSingleCategory (subheader) {
    $("#gallery").append($("<h3 class=\"subcat\">" + subheader.name + "</h3>"));

    $.ajax({
      url: "http://localhost/mysite/wp-json/wp/v2/posts?categories=" + subheader.id + "",
      dataType: "json",
      contentType: "GET",

      success: showSubcategoryItems, // Show items in subcategory

      error: handleAjaxError
   });
 }

if (subheaders.length > 0) { //If there are subcategories
   for (i = 0; i < subheaders.length; i++) {
     showSingleCategory(subheaders[i]);
   }
}

最佳答案

由于 ajax 的异步性,所有“成功”调用都保证在所有 <h3> 之后发生。已附加元素。因此出现了您所描述的症状。

通过保留对 header 元素的引用并在其后插入由 showSubcategoryItems(data) 组成的任何内容,可以轻松克服此问题。 .

function showSingleCategory (subheader) {
    // keep reference to the appended <h3>
    var $header = $("<h3 class=\"subcat\">" + subheader.name + "</h3>").appendTo("#gallery");

    $.ajax({
        url: "http://localhost/mysite/wp-json/wp/v2/posts?categories=" + subheader.id + "",
        dataType: "json",
        contentType: "GET",
        success: function(data) {
            // Show items in subcategory after the corresponding header
            $(showSubcategoryItems(data)).insertAfter($header),
        }
        error: handleAjaxError
    });
}

if (subheaders.length > 0) { //If there are subcategories
    for (i = 0; i < subheaders.length; i++) {
        showSingleCategory(subheaders[i]);
    }
}

showSubcategoryItems()将具有以下一般形式:

function showSubcategoryItems(data) {
    var html = .....; // compose html from data
    return html;
}

通过同步附加 header ,可以保证它们的顺序与原始 subheaders 一致。无论 ajax 响应的接收顺序如何。

关于jquery - 如何在 '.append()'循环内同步 'for'和ajax查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48012487/

相关文章:

javascript - 无法使用 Javascript 更改 span 元素的文本

jQuery:在附加 Ajax 请求后隐藏 Ajax 加载的 Div

PHP 在提交到 mySQL 时保存了两次

php - 如何在表单中显示从数据库中取出的数据

javascript - 链接到 WordPress 的外部 javascript

php - 如何将CSS应用于Wordpress/Woocommerce中除某些产品页面之外的所有页面?

javascript - jQuery Flot : Set width of chart (without labels)

jquery - 呈现数据表 bool 列

javascript - jQuery Mobile - 使用 URL 参数打开可折叠集

ajax - JSF/Rich Faces 中的 data.foo 语法是什么