【问题标题】:ajax within each loop executing incorrectly每个循环中的 ajax 执行不正确
【发布时间】:2012-10-16 22:24:29
【问题描述】:

我有以下js sn-p:

cat_images = $(".category-description").next().find("img");
cat_images.each(function () {
    url = $(this).parent().attr("href");
    id = url.split("id=");
    id = id[1];
    url = "cat_url.php?i="+id;
    this_image = this;

    $.get (url, function (data) {
        $(this_image).attr("src", data);
    });
 });

目前,只有每个循环迭代的最后一个元素被 ajax.get 部分更新。我认为这与 ajax 与循环交互不佳有关,因为在 ajax 函数中使用 this 会使其完全失败。

无论如何,在等待 ajax 在 Jquery 中完成时是否有延迟循环? (不希望混入常规 js)

【问题讨论】:

  • 这是因为get 函数是非阻塞(异步)的,这意味着each 循环会继续进行而不等待响应。当您从任何 get 调用获得响应时,您已经完成迭代,this_image 等于最后一个。有关如何处理此问题,请参阅下面 Vega 的答案。

标签: jquery ajax each


【解决方案1】:

尝试将其包裹在闭包中,

cat_images.each(function () {
    url = $(this).parent().attr("href");
    id = url.split("id=");
    id = id[1];
    url = "cat_url.php?i="+id;
    this_image = this;

    (function (this_image) {
      $.get (url, function (data) {
        $(this_image).attr("src", data);
      });
    })(this_image);
 });

【讨论】:

  • 干杯!自从我什至考虑使用 js 闭包已经过去了 - 我从来没有想过。
  • 我最初的想法是使用闭包,然后我想我可能想多了:(。+1
  • 另一种方法是使用 $.ajax 并将 this_image 作为上下文传递
【解决方案2】:

虽然看起来 Vega 的解决方案工作正常,但我建议你稍微改变一下逻辑。

问题是,如果您有 10 个 cat_images,您将发出 10 个不同的请求,这不是很优雅。

您应该考虑创建一个新的 cat_url.php,它会接收一个或多个 id 并一次返回所有 URL。您还可以将 html 中的图像标识为 cat_image,因此当您将 URL 作为 JSON 返回时,您可以设置每个 src。

你的 HTML sn-p 应该是这样的:

<a href="url?id=1">
  <img src="..." id="cat_image1" rel="1" />
</a>

那将是你的最终 js sn-p:

var ids = [];
cat_images.each(function () {
  ids.push($(this).attr("rel"));
});

var data = "ids=" + ids;
$.get ({
  url: url,
  data: data,
  dataType: 'json',
  success: function (data) {
    for (var img in data.images) {
      $("#cat_image" + img.id).attr("src", img.url);
    };
  }
});

你的 cat_images.php 应该返回一个像这样的 JSON:

{
  images: [
    {id: 1, url: 'url1.jpg'},
    {id: 2, url: 'url2.jpg'},
    {id: 3, url: 'url3.jpg'}
  ]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    相关资源
    最近更新 更多