python ajax post 400错误请求

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

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

  1. <form id="translationForm">
  2. <label for="russianWord">Russian Word:</label><br>
  3. <input type="text" id="russianWord" serialize-as="russianWord" name="russianWord"><br>
  4. <label for="englishWord">English word:</label><br>
  5. <input type="text" id="englishWord" serialize-as="englishWord" name="englishWord">
  6. <input type="submit" value="Submit">
  7. </form>
  8. <script>
  9. $(function () {
  10. $('#translationForm').on('submit',function (e) {
  11. $.ajax({
  12. type: 'POST',
  13. url: "{{url_for('addTran')}}",
  14. data: $('#translationForm').serialize(),
  15. contentType: "application/j-son;charset=UTF-8",
  16. dataType: "json",
  17. success: function () {
  18. alert("It worked!");
  19. }
  20. });
  21. e.preventDefault();
  22. });
  23. });

这是我的Python路线

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

pxyaymoc1#

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

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

  1. contentType: "application/json",
dauxcl2d

dauxcl2d2#

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

相关问题