简体   繁体   English

将数据从 javascript 前端发送到 Flask 后端而不使用 Ajax 的方式

[英]Way to send data from javascript front-end to Flask back-end WITHOUT Ajax

I need to send data from my javascript front-end to my python back-end in my flask app.我需要将数据从我的 javascript 前端发送到我的 flask 应用程序中的 python 后端。 I cannot use input html tags.我不能使用输入 html 标签。 Is there any way to send information to the Flask backend without using Ajax?有什么方法可以在不使用 Ajax 的情况下将信息发送到 Flask 后端?

Edit: Found an answer编辑:找到答案

I encountered the very same issue recently, and this is how I did it (although you say you can't use input tags which I don't quite understand how?, sorry if this doesn't help you then).我最近遇到了同样的问题,我就是这样做的(虽然你说你不能使用我不太明白的输入标签?如果这对你没有帮助,对不起)。 At the top of my html I created a form with an input, but gave it display none so that it stays invisible:在我的 html 的顶部,我创建了一个带有输入的表单,但没有给它显示,因此它保持不可见:

<form id='exampleForm' method = 'post' action='#' style='display:none'>
    <input id='exInput' type='text' name='exInput'>
</form>

You have to give a name to the input to be able to access it from your Flask.您必须为输入命名才能从 Flask 访问它。 Then the trick is that once you've done everything you need to do on this page, which form me was at the end of a conditional, you set the 'value' attribute of the 'exInput' text input box to what you want it to be, supposedly it has been stored in a Javascript Array previously.然后诀窍是,一旦你在这个页面上完成了你需要做的所有事情,我在条件的末尾,你将'exInput'文本输入框的'value'属性设置为你想要的应该是,据说它以前已经存储在 Javascript 数组中。 And then finally you submit the form.最后你提交表格。


var exInput = document.getElementById('exInput')
exInput.setAttribute('value', 'jsArrayYouHaveAlreadyDefined')
document.getElementById('exampleForm').submit()

On the Flask end, you just have to check for a POST method, and retrieve the data.在 Flask 端,您只需检查 POST 方法并检索数据。 (you have to import requests beforehand) (您必须事先导入请求)

@app.route('/example/', methods = ['GET', 'POST'])
def example():
    if method == 'POST':
        exInput = request.form['exInput']

    return render_template('example.html')

Hope this helps someone, although I am still a newbie.希望这对某人有所帮助,尽管我仍然是新手。

Ok so I've found XMLHttpRequest works well.好的,所以我发现XMLHttpRequest效果很好。 You can see an example of it being used with Flask here ( base html , javascript front-end , Flask back-end ).您可以在此处看到它与 Flask 一起使用的示例( 基础 htmljavascript 前端Z9784Z2261C7B2657891 This example gets input directly from an html form but you can easily just make a new FormData object and append your own values to it.此示例直接从 html 表单获取输入,但您可以轻松地为它创建一个新的FormData object 和 append 自己的值。

There's also an example using fetch() to send data (use base html and back-end linked above as well).还有一个使用 fetch()发送数据的示例(使用基本 html 和上面链接的后端)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM