如何使用 AJAX 和后端的 python-flask 接收请求

问题描述 投票:0回答:1

我正在学习 AJAX。我正在尝试在没有

<input type="submit">
的情况下将数据发送到服务器。我在 console.log 窗口中发现了一个错误。
POST http://127.0.0.1:5000/submit 500 (INTERNAL SERVER ERROR)

在运行我的 python 文件的命令提示符下显示错误。

jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got 'key'

在主要或根 html 页面中:

<form id="myForm" action="/submit" method="POST" style="display: none;">
    <input type="hidden" name="name" value="Any_name">
    <input type="hidden" name="class" value="Any_class">
</form>

<button onclick="submit()">Submit</button>

JavaScript代码:

function submit() {
  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/submit');
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.onload = function() {
    if (xhr.status === 200) {
      console.log('Data submitted successfully');
      window.location.href = '/submit';
    } else {
      console.log('Error submitting data');
    }
  };
  xhr.send(new FormData(document.getElementById('myForm')));
};

Python代码:

@app.route("/submit", methods=['POST'])
def submit():
    data = request.form.to_dict()
    return render_template("result.html", result = data)

在哪里,result.html :

<body>
    {{ for key,value in result.items() }}
    <p>{{ key }} : {{ value }}</p>
    {{ endfor }}
</body>
javascript python ajax flask ajaxform
1个回答
0
投票

您正在使用

{{
}}
其中
{%
%}
是控制语句所需的:

<body>
    {% for key,value in result.items() %}
    <p>{{ key }} : {{ value }}</p>
    {% endfor %}
</body>
© www.soinside.com 2019 - 2024. All rights reserved.