這篇短文使用jquery。
Flask提供一個很簡單的方法來處理Ajax請求——在視圖函數中用request的屬性is_xhr來判斷,如果是true則是異步請求。
Jquery的$.getJSON()方法會主動向服務端發出ajax請求(不知這個理解是否正確?),服務端響應后調用$.getJSON的回調函數。在回調函數中就可以操作Html頁面上的元素了。
客戶端:ajax.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Document</title> <link href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> </head> <body> <h1>Ajax</h1> <div id="test">Show data count:</div> <script src="//cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script> <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script> $(document).ready(function(){ $.getJSON('/ajax',function(data){ $('#test').append('<span class="badge">'+data.count+'</span>'); }); }); </script> </body> </html>
服務端:
@app.route('/ajax') def y(): if request.is_xhr: y = Area.query.all() return jsonify({'count':len(y)}) return render_template('ajax.html')
--End--