删除功能在新创建的项中不起作用

2024-06-02 07:49:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个向列表中添加项目的函数和一个删除项目的函数。当我添加项目时,它会正确显示,但在刷新页面之前无法删除该项目。我正在使用Python3、flask和javascript,但我不知道为什么不能对新创建的项调用delete函数。以下是相关代码:

index.html:

const checkboxes = document.querySelectorAll('.check-completed');
for (let i = 0; i < checkboxes.length; i++) {
    const checkbox = checkboxes[i];
    checkbox.onchange = function(e) {
        console.log('click')
        const newCompleted = e.target.checked;
        const todoId = e.target.dataset['id'];
        fetch('/todos/' + todoId + '/set-completed', {
                method: 'POST',
                body: JSON.stringify({
                    'completed': newCompleted
                }),
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(function() {
                document.getElementById('error').className = 'hidden';
            })
            .catch(function() {
                document.getElementById('error').className = '';
            })
    }
}

const descInput = document.getElementById('description');
document.getElementById('form').onsubmit = function(e) {
    e.preventDefault();
    const desc = descInput.value;
    descInput.value = '';
    fetch('/todos/create', {
            method: 'POST',
            body: JSON.stringify({
                'description': desc,
            }),
            headers: {
                'Content-Type': 'application/json',
            }
        })
        //.then(response => {
        //  return response.json()
        //  data = response.json()
        //})
        .then(response => response.json())
        .then(jsonResponse => {
            const li = document.createElement('li');
            const checkbox = document.createElement('input');
            checkbox.className = 'check-completed';
            checkbox.type = 'checkbox';
            checkbox.setAttribute('data-id', jsonResponse.id);
            li.appendChild(checkbox);

            const text = document.createTextNode(' ' + jsonResponse.description);
            li.appendChild(text);

            const deleteBtn = document.createElement('button');
            deleteBtn.className = 'xbox';
            deleteBtn.setAttribute('data-id', jsonResponse.id);
            deleteBtn.innerHTML = '&cross;';
            li.appendChild(deleteBtn);

            document.getElementById('todos').appendChild(li);
            document.getElementById('error').className = 'hidden';
        })
        .catch(function() {
            console.error('Error occurred');
            document.getElementById('error').className = '';
        })
}

删除代码

const deletes = document.querySelectorAll('.xbox');
for (let i = 0; i < deletes.length; i++) {
    const btn = deletes[i];
    btn.onclick = function(e) {
        console.log('click')
        const todoId = e.target.dataset['id'];
        fetch('/todos/' + todoId, {
                method: 'DELETE'
            })
            .then(function() {
                const item = e.target.parentElement;
                item.remove();
            })
    }
}

app.py

@app.route('/todos/create', methods=['POST'])
def create_todo():
    error = False
    body = {}
#   description = request.form.get('description', '')
#   return render_template('index.html')
    try:
        description = request.get_json()['description']
        todo = Todo(description=description)
        #body['description'] = todo.description
        db.session.add(todo)
        db.session.commit()
        body['id'] = todo.id
        body['completed'] = todo.completed
        body['description'] = todo.description
    except:
        error=True
        db.session.rollback()
        print(sys.exc_info())
    finally:
        db.session.close()
    if error:
        abort (400)
    else:
        return jsonify(body)

Tags: idjsonfunctionbodyerrorlidescriptiondocument