显示来自 ajax 的图像 src

通过以下代码请求 img src 的路径:


$.ajax({

  url: 'api/catalogs.php?action=fetchimg&CatalogId=' + d.CategoryId,

  type: 'GET',


  dataType: "json",

  success: function(response) {


    var path = response.path;

    console.log(path);


    $.each(response, function(key, value) {

      $("#images").attr('src', value.path);

    })

  },

});

但是代码只显示一张照片,API 返回多张照片并且需要显示所有照片。为了显示我使用下面的代码。


return '<div class="container">'+

        '<div class="row justify-content-center text-center my-3"></div>'+

    '<div class="row justify-content-center text-center">'+

        '<div class="col-md-4 mb-3">'+

            '<img id="images" src="" class="img-fluid img-thumbnail"></a>'+

        '</div>'+



    '</div>'+

'</div>';


慕虎7371278
浏览 166回答 3
3回答

函数式编程

您的代码仅编辑一张图片 src。你应该在你success的$.ajax$.each(response, function(key, value){&nbsp; &nbsp; $("body").append($("<img>", { src: value.path } ));})这将为响应中的每个路径添加一个图像到正文。然后您可以开始根据您的要求修改它

Cats萌萌

最后,见下文&nbsp;$.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: 'api/catalogs.php?action=fetchimg&CatalogId='+d.CategoryId,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: 'GET',&nbsp; &nbsp; &nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; &nbsp; &nbsp; success: function(response) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var images = "";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $.each(response, function(key, value){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; images+='<div&nbsp; class="col-md-4 mb-3">'+&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '<img src="'+value.path+'" class="catalog-image img-responsive thumbnail"></a>'+&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '</div>';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#photos').html(images);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },在 HTML 上面的代码插入到下面的 div 中:<div class="container">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div id="photos" class="row justify-content-right text-right my-3"></div>&nbsp; &nbsp; &nbsp; &nbsp; <div&nbsp; class="row justify-content-right text-right">&nbsp; &nbsp; &nbsp; &nbsp; </div></div>

芜湖不芜

因为您对所有元素 (#images) 使用相同的 ID。你需要让它像 ('#images' + counter); 添加计数器一样动态化。同样的事情需要在 HTML 中改变。
打开App,查看更多内容
随时随地看视频慕课网APP