I am writing a web application using Flask and would like to use the browser.ajax function in Brython, but could not find a suitable example. It would be really nice if someone showed a short example of how to use ajax in Brython. More specifically, how to transfer the data entered by the user in the text box to the text box by clicking the submit button. Any help is much appreciated!
(I write this a few weeks after I posted the question above). I followed this tutorial on how to implement ajax in Flask ( http://runnable.com/UiPhLHanceFYAAAP/how-to-perform-ajax-in-flask-for-python ) and tried to replace jquery.ajax with Brython. Unfortunately, I still can't get it to work. Here is my code:
Flask:
@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)
britt / 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>
What I get is the "result": 0. It looks like brython is not sending data to the flag viewer, but I don't know how to fix it. So, it would be great if someone could indicate exactly what I am doing wrong.
source share