python ajax post 400错误请求

of1yzvn4  于 2021-07-14  发布在  Java
关注(0)|答案(2)|浏览(469)

我正在尝试使用ajax将数据从表单发送到python flask。我不想重新加载页面。当我试图发送表单时,我得到了一个错误 POST http://127.0.0.1:5000/addTran 400 (BAD REQUEST) 我只想输入一个俄语单词和一个英语翻译,然后把它从flask写进一个文件。这是我的html和javascript

<form id="translationForm">
  <label for="russianWord">Russian Word:</label><br>
  <input type="text" id="russianWord" serialize-as="russianWord" name="russianWord"><br>
  <label for="englishWord">English word:</label><br>
  <input type="text" id="englishWord" serialize-as="englishWord" name="englishWord">
  <input type="submit" value="Submit">
</form>

<script>
    $(function () {
        $('#translationForm').on('submit',function (e) {

              $.ajax({
                type: 'POST',
                url: "{{url_for('addTran')}}",
                data: $('#translationForm').serialize(),
                contentType: "application/j-son;charset=UTF-8",
                dataType: "json",
                success: function () {
                 alert("It worked!");
                }
              });
          e.preventDefault();
        });
    });

这是我的Python路线

@app.route('/addTran',methods=["POST"])
def addTran():
    if request.method == "POST":
        tran = request.get_json(force=True)
        with open('/home/matt/Desktop/info.txt','w') as w:
            w.write(str(tran))
pxyaymoc

pxyaymoc1#

也许是请求内容类型的错误?

contentType: "application/j-son;charset=UTF-8",

contentType: "application/json",
dauxcl2d

dauxcl2d2#

添加json.stringify()成功了! data: JSON.stringify($('#translationForm').serialize())

相关问题