本次使用文件的目录结构,flask的特别要求需要静态文件放到static文件夹下面,结论就是HTML写好放到templates下面引用的时候使用../static/***引用
# main.py
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('ajaxIndex.html')
# 特别注意的是request.args['**']获取get请求的参数
# request.form['**']获取post请求的参数,request.values['**']可以获得两种方式的参数
@app.route('/ajax')
def ajax():
return 'get获取到'+request.args['name']
# 当两种方式分开写时函数注意不要重名
@app.route('/ajax', methods=['POST'])
def ajax_post():
return 'post获取到'+request.values['name']
app.run()
<!--ajaxIndex.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajaxIndex</title>
<script src="../static/jquery-3.3.1.min.js"></script>
<script src="../static/ajaxIndex.js"></script>
</head>
<body>
<input type="text" id="namevalue"><br/>
<button id="btn">send</button>
结果:<span id="result"></span>
</body>
</html>
//ajaxIndex.js
$(document).ready(function () {
$('#btn').on('click',function () {
//此时使用的是post方式,get方式直接换成get就行
$.post('/ajax', {name:$('#namevalue').val()}, function(data){
$('#result').text(data);
})
})
})
最后的一个疑问是直接不通过127.0.0.1:500访问的话就不能正确显示,而且使用localhost也不行
flask路由传参方式
@app.route('/<name>')
def other(name):
return render_template(name)