Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
66 views
in Technique[技术] by (71.8m points)

javascript - no 'DATA' attribute in request in my view.py

i'm trying to pass data with js in function UpdateUserOrder

$(document).ready(function() {
    document.querySelectorAll('.update-cart').forEach(item =>{
        item.addEventListener('click', () => {
            var productId = item.dataset.product
            var action = item.dataset.action
            if(user === 'AnonymousUser'){
                console.log('not logged in')
            }else{
                UpdateUserOrder(productId, action)
            }
        })
    })
})

function UpdateUserOrder(productId, action){
    console.log('user logged in')

    var url = 'add_to_cart/'

    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type':'application/json',
            'X-CSRFToken': csrftoken,
        },
        body:JSON.stringify({'productId':productId,'action':action})
    })
    .then((response) =>{
        return response.json()
    })
    .then((data) =>{
        console.log('data', data)
    })
}
{% for product in products %}
    <div>
        <label id="title-label" for="title">Title</label>
        <p id="title">{{ product.title }}</p>
        <label id="author-label" for="author">Author</label>
        <p id="author">{{ product.author }}</p>
        <label for="user">Seller</label>
        <p id="user">{{ product.user }}</p>
        <p><img src="{{ product.image }}" alt="none"></p>
        <a id="link" href="{% url 'market_detail' product.id %}">Details</a>
        <button data-product="{{ product.id }}" data-action="add" class="update-cart">add</button>
    </div>
{% endfor %}
question from:https://stackoverflow.com/questions/65941071/no-data-attribute-in-request-in-my-view-py

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are sending the data through the request body (body:JSON.stringify({'productId':productId,'action':action})), which means you have to access it in views.py:

data = json.loads(request.body)

Also, you can always check the attributes of an object with the dir built-in.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...