我正在使用Flask编写Web应用程序,并希望在Brython中使用browser.ajax功能,但找不到可行的示例.如果有人演示如何在Brython中使用ajax,那将是非常好的.更具体地说,如何通过单击提交按钮将用户输入的数据传递到文本域中.任何帮助都非常感谢!
(我在发布上述问题几周后就写了这篇文章).我按照本教程关于如何在Flask(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',type=int) b = request.args.get('b',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的视图函数发送数据,但我不知道如何解决这个问题.所以,如果有人可以指出我做错了什么,那就太好了.
解决方法
在您的示例中,使用方法GET发送Ajax请求.在这种情况下,将忽略send()的参数:必须在附加到url的查询字符串中发送数据
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),'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',type=int) b = request.form.get('b',type=int) return jsonify(result = a+b)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。