jQuery和flask使用ajax实践

本次使用文件的目录结构,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)

  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值