python小菜 2014-12-02 19:24 采纳率: 0%
浏览 31

使用AJAX加载图像

I need to load 3 images from another page. This is my code

<script>
jQuery(document).ready(function($) {
  var ids = ['#sk6x4', '#sk6x4a', '#sk6x4c'];
  var tabs = ['#tab1', '#tab2', '#tab3'];
  function getInfo() {
  $.each(ids, function (i, id) {
      $.ajax('/my-url', {
        success: function(data){
          var imgSrc = $(data).find(ids[i] + ' img').attr('src');
          $(tabs[i] + ' img').attr('src', imgSrc);
        }
      });
  });
  }
});
</script>
<ul class="nav nav-tabs" role="tablist">
  <li class="active" id="tab1"><img src="" id="imageTriangle"/></li>
  <li id="tab2"><img src="" id="imageArc"/></li>
  <li id="tab3"><img src="" id="imageScat"/></li>
</ul>

This code works but wery slow. Images load very slowly. How i can make it faster? What is the right way to load images by ajax?

P.S. Images are optimized

  • 写回答

1条回答 默认 最新

  • weixin_33712881 2014-12-02 19:55
    关注

    First of all, you are making multiple ajax requests. It would be better to make just one, and return the URLs with JSON or something. Secondly, you don't even need ajax to load images. You can do like this:

    $(document).ready(function () {
    var ids = ['#sk6x4', '#sk6x4a', '#sk6x4c'];
    var tabs = ['#tab1', '#tab2', '#tab3'];
    function getInfo() {
        $.ajax('/my-url', { // ajax call to get urls
            success: function (data) {
                $.each(ids, function (i, id) {
    
                    var imgSrc = data.urls[i] //assuming that data is an array that contains the urls
                    var img = $("<img /> ").attr('src', imgSrc).load(function () {
                        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                            alert('Error...!');
                        }
                        else {
                            $(tabs[i]).html()
                        }
                    });
    
                });
            }
        });
    }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条