Flask之ajax操作示例

`文末包含源码`

python3.6,flask使用简例,

 目录结构

index2.html 

<html><head>
    <link href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type=text/javascript src="{{
        url_for('static', filename='jquery.js') }}"></script>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
</head>
<body>
    <script type=text/javascript>
        $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
      </script>


<script type=text/javascript>
    $(function() {
      $('a#calculate').bind('click', function() {
        $.getJSON($SCRIPT_ROOT + '/_add_numbers', {
          a: $('input[name="a"]').val(),
          b: $('input[name="b"]').val()
        }, function(data) {
          $("#result").text(data.result);
        });
        return false;
      });
    });
  </script>
  <h1>jQuery Example</h1>
  <p><input type=text size=5 name=a> +
     <input type=text size=5 name=b> =
     <span id=result>?</span>
  <p><a href=# id=calculate>calculate server side</a>
</body>

myserver2.py

# coding:utf-8

from flask import *
from flask import request

app = Flask(__name__)

@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)

@app.route('/')
def index():
    html=render_template('index2.html')
    return html

@app.route('/test_post', methods=['GET', 'POST'])
def test_post():
    return '{"name":"zhangsan"}'

if __name__=='__main__':
    app.run(debug=True,host="0.0.0.0")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JavaPub-rodert

谢谢老板

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值