[英]Flask: How to send a dictionary job from JavaScript to python
I want to send a object called accounts
which contains various details like name, email, type etc. Which can be accessed by account.name
and so on.我想发送一个名为
accounts
的对象,其中包含各种详细信息,如姓名、电子邮件、类型等。可以通过account.name
等访问。
I want to transfer this object from javascript to flask route.我想将此对象从 javascript 转移到烧瓶路线。 My app.py is
我的 app.py 是
@app.route('/completed')
def completed(variable):
return "<h1>done {}</h1>".format(variable)
My javascript我的 JavaScript
function(accounts) {
window.location = ('{{ url_for('completed', variable='accounts') }}')
}
It is giving me an error它给了我一个错误
TypeError: completed() missing 1 required positional argument: 'variable'
This jinja code这个金贾代码
url_for('completed', var='foo')
would require this flask route需要这条烧瓶路线
@app.route('/completed/<var>')
def completed(var):
But in this case, foo
is just a simple string.但在这种情况下,
foo
只是一个简单的字符串。 If you want to pass a whole js object, I would use javascript to convert it to json, then use fetch()
to POST it to the route with a json mime type, then read it in flask like so如果你想传递整个 js 对象,我会使用 javascript 将它转换为 json,然后使用
fetch()
将它发布到带有 json mime 类型的路由,然后像这样在烧瓶中读取它
from flask import request
@app.route('/completed', methods=['POST'])
def completed():
data = request.get_json()
return 'result is ok'
Edit: how to post json with fetch()编辑:如何使用 fetch() 发布 json
fetch('/completed', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(your_js_object)
})
.then(response => response.text())
.then(result => console.log(result));
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.