如何在Brython中使用ajax
发布时间:2020-12-16 02:53:25 所属栏目:百科 来源:网络整理
导读:我正在使用Flask编写Web应用程序,并希望在Brython中使用browser.ajax功能,但找不到可行的示例.如果有人演示如何在Brython中使用ajax,那将是非常好的.更具体地说,如何通过单击提交按钮将用户输入的数据传递到文本域中.任何帮助都非常感谢! (我在发布上述问题
我正在使用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的查询字符串中发送数据
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),'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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |