samedi 29 février 2020

How can I display the data in the right table by using javascript for-loop and if-satement?

I have some data fetching by ajax, I need to use for-loop and if-statement to check which good belongs to whose shopping cart. And then display in their table. The for-loop and if-statement I write worked correctly in HTML, now I just use the same logic to write in js file. But it fails. My code always puts all the data in one table. Which part do I miss it? I scratch my head for a long time and can not fix it.

test.js

function createTable() {
        $.ajax({
                url: "http://127.0.0.1:8000/test2",
                type: "GET",
                success: function (result) {
                    var mybody = document.getElementById("myDynamicTable");
                    var customer_status = (result);
                    var customers = JSON.parse(customer_status.Customer);
                    var carts = JSON.parse(customer_status.Cart);
                    var goods = JSON.parse(customer_status.Good);
                    for (var p in customers){
                        for (var c in carts){
                            if(customers[p].pk == carts[c].fields.customer){
                                for (var g in goods){
                                    if (carts[c].pk == goods[g].fields.cart){
                                        var tr2 = document.createElement('TR');
                                        tr2.className="trClass";
                                        var td1 = document.createElement('TD');
                                        var td2 = document.createElement('TD');
                                        var td3 = document.createElement('TD');
                                        var td4 = document.createElement('TD');
                                        td1.appendChild(document.createTextNode(goods[g].fields.name));
                                        td2.appendChild(document.createTextNode(goods[g].fields.count));
                                        td3.appendChild(document.createTextNode(goods[g].fields.price));
                                        td4.appendChild(document.createTextNode(goods[g].fields.count*goods[g].fields.price));
                                        tr2.appendChild(td1);
                                        tr2.appendChild(td2);
                                        tr2.appendChild(td3);
                                        tr2.appendChild(td4);
                                        mybody.appendChild(tr2);
                                    }
                                }
                            }
                        }
                    }
                }
            })
            $(".trClass").remove();
}

for example, I use the admin site to add two cokes to the second customer, but it still displays under the fisrt customer.

pic1

please help! thank you.

Aucun commentaire:

Enregistrer un commentaire