jQuery中ajax(基于Flask框架做的后端演示)

一、jQuery复杂请求

app.py

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/ajax/js',methods=['GET','POST'])
def ajax_js():
    return 'js_ajax',200  # 200表示请求ajax/js网址所返回的状态码

@app.route('/ajax/jq')
def ajax_jq():
    return  render_template('ajaxjq.html')

if __name__ == '__main__':
    app.run()

ajaxjq.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/static/js/jquery-3.4.1.min.js"></script>
</head>
<body>
<p>jquery 中使用 ajax</p>
<a href="javascript:;">点击提交</a>
<script>
    $(document).ready(function () { //$(document).ready(function(){})在整个document完成再用这个调用
        $('a').click(function () {
            $.ajax({
                url: 'http://127.0.0.1:5000/ajax/js',
                method: 'GET',//也可以改为POST请求
                data: { // get下的data是附带在网址后面的参数 
                    username: 'zhangsan',
                    password: '123123'
                },
                success: function (res) { // 200请求成功
                    console.log(res)
                    console.log('请求成功')
                },
                error: function () {//200以外的就是请求失败
                    alert('出错了')
                },
                complete: function () {//无论你是请求成功还是失败,都是请求完成了,会显示成功
                    alert('请求完成了')
                }
            })
        })
    })
</script>
</body>
</html>

逻辑:网页请求/ajax/jq → 点击a标签 → 请求/ajax/js信息,返回’js_ajax’ ,ajax_js视图函数收到被请求,打印request.values

请添加图片描述

二、jquery的ajax快捷函数

增加/ajax/shortcut访问路径

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/ajax/js',methods=['GET','POST'])
def ajax_js():
    print(request.values)
return 'js_ajax' 

@app.route('/ajax/shortcut',methods = ['GET','POST'])
def ajax_shorcut():
    return render_template('jajax_shortcut.html')

if __name__ == '__main__':
    app.run()

jajax_shortcut.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax 快捷函数的使用</title>
    <script src="/static/js/jquery-3.4.1.min.js"></script>
</head>
<body>
<p>ajax 快捷函数的使用</p>
<a href="javascript:;">点击提交</a>
<script>
    $(document).ready(function () {
        $('a').click(function () {
            $.get('http://127.0.0.1:5000/ajax/js', {
                'username': 'zhangsan',
                'password': '123123'
            }, function (res) {
                console.log(res);
                console.log('请求成功')
            })
        })
    })
</script>
</body>
</html>

解释:

post请求不会把data的数据方法url后面
在这里插入图片描述
get请求则会把data的参数放在url后面
在这里插入图片描述

三、getJSON

app.py

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/ajax/js',methods=['GET','POST'])
def ajax_js():
    print(request.values)
    import json
    user = { # json格式:多层的字典嵌套
        'username':'用户名',
        'nickname':'绰号',
        'profile':{
            'age':23
        }
    }
    return json.dumps(user) # 将json格式转换为字符串

@app.route('/ajax/shortcut',methods = ['GET','POST'])
def ajax_shorcut():
    return render_template('jajax_shortcut.html')

if __name__ == '__main__':
    app.run()

逻辑:网页请求/ajax/shortcut,渲染jajax_shortcut.html → 点击a标签 → 请求/ajax/js,返回一个被字符串格式的json,ajax_js感受到被请求,因此可以用request获取values(request.values)

jajax_shortcut.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax 快捷函数的使用</title>
    <script src="/static/js/jquery-3.4.1.min.js"></script>
</head>
<body>
<p>ajax 快捷函数的使用</p>
<a href="javascript:;">点击提交</a>
<script>
    $(document).ready(function () {
        $('a').click(function () {
            $.get('http://127.0.0.1:5000/ajax/js', {
                'username': 'zhangsan',
                'password': '123123'
            }, function (res) {
                console.log(res);
                console.log(res['username'])
                console.log('请求成功')
            })
        })
    })
</script>
</body>
</html>

在这里插入图片描述
解释:为什么这儿第二个log是undefined?因为get请求返回的数据是字符串格式的(因为ajax_js视图函数使用json.dumps将json格式转换为字符串格式了),而不是json格式,因此无法使用res[‘username’]获取对应的数据。

解决办法:

①将get请求方式改为getJSON格式,他会自动将字符串格式转换为JSON格式

$.getJSON(‘http://127.0.0.1:5000/ajax/js’)

②html里有JSON.parse(字符串格式的json),也可以将字符串格式的json转换为json格式

笔记素材来源:拉勾大前端训练营。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值