简体   繁体   中英

How do i dynamically display my json decoded data into a ul

i am sorry if this question has been asked before I couldn't seem to find something to answer this.

Below is my Json decoded array:

cart_id:1
cart_items:
  1:
    cost:4
    name:"Titleist Pro V1"
    quantity:4
  2:
    cost:1
    name:"Titleist Pro V1x"
    quantity:1

How can i dynamically display this into html using JQuery or javascript? I have figured out to be able to display a single variable by using this:

$result['cart_items']['1']['name'];

This will give me "Titleist Pro V1" in return. I am struggling with a lot of errors from all sides and felt the code itself would be too messy to paste here. It would be amazing if somebody could please just show me how i can dynamically create this data into an ul using the next pasted format with a loop or something.

<ul>
  <li> $name x $quantity <br> cost: $cost</li>
  <li> $name x $quantity <br> cost: $cost</li>
</ul>

EDIT: I meant to show the top list bit as pure html but stackoverflow is converting it too an actual list, i hope its still understandable.

NOTE: My data is brought in from a database through laravel/php. i receive an json encoded file that i then proceed to decode with:

$result = jQuery.parseJSON(result);

I need to be able to take any amount of results and display a list of items and their costs. Sorry if this is a lot of trouble, I'm struggeling with Laravel at the moment and things feel very overwelming.

Thank you for all your help in advance!

Assuming your JSON to be in the below format

$result = {
  "cart_id" : 1,
  "cart_items": {
      "1": {
        cost:4,
        name:"Titleist Pro V1",
        quantity:4
      },
      "2": {
        cost:1,
        name:"Titleist Pro V1x",
        quantity:1
      }
  }
};

You could use jQuery each method to loop through the object to generate an <ul> using the code below

var b = "<ul>";

$.each($result['cart_items'], function(property, value) {
  b += "<li>" + value['cost'] * value['quantity'] + "<br/>" + "cost " + value['cost'] + "</li>";
});

b += "</ul>";

$(".container").html(b);

Codepen: https://codepen.io/anon/pen/xdLEBb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM