flask+web+ajax练习
2020-01-19 本文已影响0人
独步江雪
from flask import Flask, url_for, request
from jinja2.utils import generate_lorem_ipsum
# from urllib.parse import urlparse, quote
app = Flask(__name__)
@app.route('/articles/<int:id>')
def ajax_article(id):
path = url_for('more_para', id=id)
para_num = 2
first_body = generate_lorem_ipsum(n=para_num)
html = '''
<h1>文章%s</h1>
<div class="body">%s</div>
<button id='load'>加载更多</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(function(){
var para_num =%d;
$('#load').click(function(){
$.ajax({
url:'%s',
type:'get',
data:'para_num='+String(para_num),
success:function(data){
$('.body').append(data);
}
})
para_num++;
})
})
</script>
''' % (id, first_body, para_num + 1, path)
return html
@app.route('/articles/<int:id>/more')
def more_para(id):
para_num = request.args.get('para_num')
return '文章{}的第{}段<br/>'.format(id, para_num)
if __name__ == '__main__':
app.run()