如何循环ajax响应并在html中显示它?

How do i loop through an ajax response and display it in html

本文关键字:html 显示 响应 何循环 循环 ajax      更新时间:2023-09-26

我是一个PHP开发人员,我正在寻找像foreach循环的ajax响应

我在html中有一个卡片设计,我希望ajax请求的响应为ajax响应中的每个对象创建一个新的卡片

这是far 的代码ajax:

  $.ajax({
        type:"GET",
        url:"http//url_to_api.com/projects/v1" ,
        dataType: "json",
        success:function(mdata){
             var  result =  '';           
              $.each(mdata,  function (index, element) {               
                result +=    + element.project_name ;  
                console.log(element.project_name); // alert the values 
              });           
              $('.cho-card-title').html(result);

         }
   });
我希望ajax响应为响应数据中的每个对象填充的

html

<div class="card-row">          
    <div class="card">
        <div class="card-img"> 
            //image.of.ajax.responce
            <img src=""> 
        </div>
        <div class="card-title">
           // title.of.ajax.responce
        </div>
        <div class="card-description">
         //    title.of.ajax.description
        </div>             
        <div class="select-card">
            Select
        </div>          
    </div> 
</div>  

当前,代码循环遍历响应并在一张卡片中显示所有内容,我如何在自己的卡片中获得每个响应

您可以在.each语句中创建和追加元素。

这是未经测试的,但像这样的东西可能有效:

$.each(mdata,  function (index, element) {          
  var div = $('<div />') // Create the div
             .addClass('cho-card-title') // Add the class name
             .html(element.project_name); // Insert the html
  // Append the new div to whatever your container is
  $('.container').append(div);
});