我正在使用Flask编写一个web应用程序,并且希望在Brython中使用browser.ajax功能,但是找不到一个可行的例子。如果有人演示了如何在Brython中使用ajax的简短示例,那就太好了。更具体地说,如何通过单击submit按钮将用户输入的数据传递到textfield中。任何帮助都是非常感谢的!
(在我贴出上述问题几周后,我正在写这封信)。我遵循了本教程关于如何在http://runnable.com/UiPhLHanceFYAAAP/how-to-perform-ajax-in-flask-for-python中实现ajax的教程,并尝试用Brython替换jquery.ajax。不幸的是,我还是不能让它起作用。这是我的代码:
烧瓶的部分:
@app.route('/')
def index():
return render_template('index.html')
@app.route('/_add_numbers')
def add_numbers():
a = request.args.get('a', 0, type=int)
b = request.args.get('b', 0, type=int)
return jsonify(result=a + b)Brython/HTML:
<body onload="brython()">
<script type="text/python">
from browser import document as doc
from browser import ajax
def on_complete(req):
if req.status==200 or req.status==0:
doc["txt_area"].html = req.text
else:
doc["txt_area"].html = "error "+req.text
def get(url):
req = ajax.ajax()
a = doc['A'].value
b = doc['B'].value
req.bind('complete',on_complete)
req.open('GET',url,True)
req.set_header('content-type','application/x-www-form-urlencoded')
req.send({"a": a, "b":b})
doc['calculate'].bind('click',lambda ev:get('/_add_numbers'))
</script>
<div class="container">
<div class="header">
<h3 class="text-muted">How To Manage JSON Requests</h3>
</div>
<hr/>
<div>
<p>
<input type="text" id="A" size="5" name="a"> +
<input type="text" id ="B" size="5" name="b"> =
<textarea type="number" class="form-control" id="txt_area" cols="10" rows = '10'></textarea>
<p><a href="javascript:void();" id="calculate">calculate server side</a>
</div>
</div>
</body>
</html>我得到的是“结果”:0。看起来brython没有将数据发送到Flask的视图函数,但我不知道如何解决这个问题。所以,如果有人能指出我到底做错了什么,那就太好了。
发布于 2014-12-02 10:44:16
在您的示例中,Ajax请求与GET方法一起发送。在本例中,send()的参数被忽略:数据必须在附加到url的查询字符串中发送。
Brython代码应该是:
def get(url):
req = ajax.ajax()
a = doc['A'].value
b = doc['B'].value
req.bind('complete',on_complete)
# pass the arguments in the query string
req.open('GET',url+"?a=%s&b=%s" %(a, b),True)
req.set_header('content-type','application/x-www-form-urlencoded')
req.send()如果您想使用POST方法,那么可以保持原样的Brython代码,但是应该修改Flask代码:您必须指定函数处理POST请求,然后使用属性"form“而不是"args”获得参数:
@app.route('/_add_numbers_post', methods=['POST'])
def add_numbers_post():
a = request.form.get('a', 0, type=int)
b = request.form.get('b', 0, type=int)
return jsonify(result = a+b)发布于 2014-11-25 16:47:00
我正在进行这方面的工作--还没有做好任何准备,但是编写Python代码使它变得非常无痛。
我无法发布我正在处理的代码(而且这远远不是最小的)--但基本上,您编写了一个(Br)Python函数来迭代HTML或form DOM,并收集json结构中具有“值”的所有内容(一个包含嵌套的dictionary和列表的字典)--它们您只需使用http://brython.info/doc/en/index.html#中记录的browser.ajax对象,并将数据作为参数传递给"send“方法。
请求体中的对象数据将是URLencoded。您只需在客户端将其解码为JSON即可。
作为一个额外的提示:我没有深入探讨这个问题,但我觉得默认使用的URLencoding可能无法表达所有在JSON中可能使用的内容。因此,导入brython的json模块,并执行以下发送:
ajax_object.send({"data": json.dumps(json_data)})
这允许我在客户端:json_data = json.loads(urllib.unquote(request.body).split(":",1)[-1] )上执行此操作。
( "request.body“来自金字塔-对于烧瓶来说,它是"request.data",但只有当容器类型无法被烧瓶检查How to get data received in Flask request所理解时)
https://stackoverflow.com/questions/26021672
复制相似问题