【问题标题】:javascript python 3 jsonResponse undefinedjavascript python 3 jsonResponse 未定义
【发布时间】:2020-05-08 18:53:21
【问题描述】:

我正在尝试向我的服务器发送一个发布请求,然后立即更新网页以显示用户输入。看起来 POST 请求正在通过,因为当我刷新页面时,会显示用户输入并且正确的数据已插入到我的数据库中。问题是当我提交表单时,页面显示未定义的数据。在刷新页面之前,我无法更新或删除该项目。为什么提交的数据没有立即显示在页面上?这是我的相关代码。

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)

【问题讨论】:

    标签: javascript python-3.x flask sqlalchemy


    【解决方案1】:

    我明白了。我没有为我的 json 对象设置必要的属性并在 app.py 中返回它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-22
      • 1970-01-01
      • 1970-01-01
      • 2012-11-03
      • 2023-01-11
      • 1970-01-01
      • 2010-10-21
      相关资源
      最近更新 更多