Home > Net >  JSON loop through data and print into div
JSON loop through data and print into div

Time:10-11

I am grabbing some data via URL from an external site (Cross Origin..) and I want to display the results (for each) into their own html div's.

How do I go about this, what is the simplest effective method?

Here is the current code

<script>
    $.ajax({
    dataType: "json",
    url: 'https://*****************/DirectDownload/GetShopProducts?token=*********&searchString=polo',
    success: function(products){
        var html = '<div>';
          $.each(products, function (index, value) {
              html  = '<h2>Item Code:</h2><p>'   value.ItemCode   '</p>';
          });
          html  = '</div>';
          $('#output').html(html);
  }
  });
  </script>

The results in console log

[

{
"ItemCode":"1100-M-NV-FER03EM2-FER",
"Description":"Osprey Deluxe Poloshirt",
"TechnicalInfo":"",
"ImageName":"1100NAR.jpg",
"FfProductCode":"1100-M-NV-EM2-FER",
"CategoryDescription":"PoloShirts",
"CategoryImage":"******.**.**/web/images/category_poloshirt.jpg"
},

{
"ItemCode":"1160-20-NV-FER03EM1-FER",
"Description":"Wren Ladies Poloshirt",
"TechnicalInfo":"",
"ImageName":"1160NAR.jpeg",
"FfProductCode":"1160-20-NV-EM1-FER",
"CategoryDescription":"Polo Shirts",
"CategoryImage":"https://******.**.**/web/images/category_poloshirt.jpg"
}

]

I want to achieve something like below

<script>
      $.ajax({
    dataType: "json",
    url: 'https://*****************/DirectDownload/GetShopProducts?token=*********&searchString=polo',
    success: function(products){

     for each { 

     <div>
     <h2>Item Code:</h2><p>$ItemCode</p>
     <h2>Item Code:</h2><p>$description</p>
     ....
     </div>

     }

    });
    </script>

CodePudding user response:

Something like this?:

success: function(data){
      var html = '<div>';
        $.each(data, function (index, value) {
            html  = '<h2>Item Code:</h2><p>'   value.ItemCode   '</p>';
        });
        html  = '</div>';
        $('#result').html(html); //here you set the html variable with the collected data into your desire html tag.
},
  • Related