简体   繁体   中英

How to Access values from dictionary in Javascript

I am try to fetch my item_id field from model.py in django in query set form that below

<QuerySet [<Item: Shoulder Bag Boys Shoulder Bag (Yellow )>,
<Item: Sweeter Cotton Sweeter>,
<Item: Shirt Full Sleeves Shirt>, <Item: Jacket Jackson Jacket>, 
<Item: Yellow Shoes Leopard Shoes>, 
<Item: Bag Mini Cary Bag>, <Item: Coat Overcoat (Gray)>,
<Item: TOWEL Pure Pineapple>,
<Item: Coat Pure Pineapple>, <Item: TOWEL Pure Pineapple (White)>]>

Here is my JS Code

 $.ajax({
            type: 'GET',
            url: '/shopsorting/' + selected_value,
            // data: formData,
            encode: true
        })
        .done(function(data) {
            items = JSON.parse(data)
            console.log(items)
            for (var item in items) {
                console.log(item['product_id'])
            };

But it print in console

`(index):765
{items: "<QuerySet [<Item: TOWEL Pure Pineapple>, <Item: Ba…s Leopard Shoes>, <Item: Jacket Jackson 
Jacket>]>"}

(index):767 undefined`

Try to convert data into a string before receiving it:

x = JSON.stringify(data); 
items = JSON.parse(x);

Don't forget the ';'

    $.ajax({
            type: 'GET',
            url: '\/shopsorting\/' + selected_value,
            // data: formData,
            encode: true,
            success: function(data) {
                x = JSON.stringify(data);
                items = JSON.parse(x);
                console.log(items);
                for (var item in items) {
                    console.log(item['product_id'])
                };
}});

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