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!
答案 0 :(得分:0)
假设您的JSON采用以下格式
$result = {
"cart_id" : 1,
"cart_items": {
"1": {
cost:4,
name:"Titleist Pro V1",
quantity:4
},
"2": {
cost:1,
name:"Titleist Pro V1x",
quantity:1
}
}
};
您可以使用jQuery each方法循环访问对象,使用下面的代码生成<ul>
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);