json字段未使用获取发送到服务器

时间:2020-04-07 16:30:03

标签: javascript ajax asynchronous fetch

我已使用AJAX提取方法将此表单提交到Flask应用程序,但是由于某种原因它没有通过服务器,我可以毫无问题地提醒输入。

<html>
    <head>
        <title>TODO App</title>
    </head>
    <style>
        .hidden {
            display: none;
        }
    </style>
    <body>
        <form id="form" >
            <input type="text" id="description" name="description" />
            <input type="submit" value="Create" />
        </form>
        <div id="error" class="hidden">Something went wrong</div>
        <uL id="todos">
            {%for d in data%}
            <li>{{d.description}}</li>
            {%endfor%}
        </uL>
    </body>
    <script>
        document.getElementById('form').onsubmit = function(e) {
            e.preventDefault();
            //alert(document.getElementById('description').value);
            let desc = document.getElementById('description').value;
            alert(desc);
            fetch('/todos/create', {
                method: 'POST',
                body: JSON.stringify({
                    'description': desc
                }),
                headers: {
                    'content-type': 'application/json'
                }
            })
            .then(function (response){
                return response.json();
            })
            .then(function(jsonResponse){
                console.log(jsonResponse);
                const liItem = document.createElement('LI');
                liItem.innerHTML = jsonResponse['description'];
                document.getElementById('todos').appendChild(liItem);
            })
            .catch(function(){
                document.getElementById('error').className = '';
            })
        }
    </script>
</html>

需要时侦听此内容的python函数:

@app.route('/todos/create', methods=['POST'])
def create_todo():
  #description = request.form.get('description', '')
  description = request.form.get_json()['description']
  todo = Todo(description=description)
  db.session.add(todo)
  db.session.commit()
  #return redirect(url_for('index'))
  return jsonfiy({
    'description' : todo.description
  })

输入id = description的文本是有问题的,我总是得到在catch中指定的错误消息。不确定是什么问题 !当python函数具有默认值时(如果该字段未被填充),该项目将被添加到数据库中没问题,但是当我删除默认值时,出现了问题,因为输入未传递到服务器上

1 个答案:

答案 0 :(得分:0)

所以问题出在

request.form.get_json()

实际应该在python函数中的位置:

request.get_json()

已修复该问题,感谢您的所有评论。