javascript python 3 jsonResponse undefined - PullRequest
0 голосов
/ 08 мая 2020

Я пытаюсь отправить почтовый запрос на свой сервер, а затем мгновенно обновляю веб-страницу, чтобы отобразить ввод пользователя. Похоже, что запрос POST выполняется, потому что, когда я обновляю sh страницу, отображается пользовательский ввод, и правильные данные были вставлены в мою базу данных. Проблема в том, что когда я отправляю форму, на странице отображаются неопределенные данные. Я не могу обновить или удалить элемент, пока не обновлю sh страницу. Почему отправленные данные не отображаются на странице сразу? Это мой соответствующий код.

index. html:

      const descInput = document.getElementById('description');
      document.getElementById('form').onsubmit = function(e) {
        e.preventDefault();
        const desc = descInput.value;
        descInput.value = '';
        response = fetch('/todos/create', {
          method: 'POST',
          body: JSON.stringify({
            'description': desc,
          }),
          headers: {
            'Content-Type': 'application/json',
          }
        })
        .then(response => {
            return 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 = 'delete-button';
          deleteBtn.setAttribute('data-id', jsonResponse.id);
          deleteBtn.innerHTML = '✗';
          li.appendChild(deleteBtn);

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

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()
    except:
        error=True
        db.session.rollback()
        print(sys.exc_info())
    finally:
        db.session.close()
    if error:
        abort (400)
    else:
        return jsonify(body)

1 Ответ

0 голосов
/ 08 мая 2020

Я понял. Я не устанавливал свой объект json с необходимыми атрибутами и не возвращал его в app.py

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...