ajax与python后端交互

ajax简介

ajax可以在页面不刷新的情况下可以与后端进行数据交互,异步提交,局部刷新。

比如百度的注册页面,我并没有点击提交它就提醒我用户已存在了。

image

ajax不是一门全新知识,本质就是一些js代码,我们学习ajax直接使用jQuery封装之后的版本(语法更加简单),使用ajax的前提必须要引入jQuery文件。

使用

前端中,ajax里的请求携带的数据一般用字典类型,便于后端接收并使用。

$.ajax({
    url:'',  // 页面请求地址,不写就是当前地址
    type:'post',  // 请求方式,不写默认为get请求
    data:{'data':'data'},  // 请求携带的数据
    success:function (args) {  // 异步回调函数,后端有回复时触发,args接收后端传来的数据
    	
	}
})

后端使用request.is_ajax()判断是否是ajax请求,并要使用Httpresponse返回给ajax异步回调函数中的形参。

def index(request):
    if request.is_ajax():  # 判断是否是ajax请求
        return Httpresponse('返回给ajax的数据')
    return render(request, 'index.html')

案例

让输入框后面来一段内容可以跟着输入框实时变化。

前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
    <p>用户名<input id="username" type="text"><span id="name" style="color:red;"></span></p>
    <script>
        $('#username').on('input', function () {
            let data = $(this).val()
            $.ajax({
                url: '',
                type: 'post',
                data: {'username':data},
                success: function (args) {
                    $('#name').text(args)
                }
            })
        })
    </script>
</body>
</html>

后端:

def index(request):
    if request.is_ajax():  # 判断是否是ajax请求
        if request.method == 'POST':
            data = request.POST
            return HttpResponse(data.get('username'))

    return render(request, 'index.html')

image

前后端传输数据编码格式

前端传输数据编码格式可以从按F12查看网络请求。

image

form表单默认发送的编码格式

Content-Type:application/x-www-form-urlencoded。

数据格式举例:username=jason&password=123。

django后端会自动处理到request.POST接收。

form表单发送文件

Content-Type:multipart/form-data。

数据格式:隐藏不让看。

django后端会自动处理:request.POST接收其他,request.FILES接收文件信息。

ajax默认的编码格式

Content-Type:application/x-www-form-urlencoded。

数据格式举例:username=jason&password=123。

django后端会自动处理到request.POST接收。

ajax发送json格式数据

Content-Type:application/json

数据格式举例:username=jason&password=123。

django后端只会用request.body接收。

ajax发送json格式数据

ajax发送的数据类型一定要跟数据的编码格式一致,如果想要发送json格式数据就需要用到json数据的编码格式application/json。

$.ajax({
    url: '',
    type: 'post',
    contentType: 'application/json',  // 不写,默认是urlencoded编码
    data: JSON.stringify({'name': 'tom'}),  // 序列化方法
    success: function (args) {
    }
})

后端只能用request.body接收,接收还需要反序列化。

def index(request):
    if request.is_ajax():
        if request.method == 'POST':
            import json
            res = json.loads(request.body)  # 反序列化
            print(res)
            return HttpResponse('666')

    return render(request, 'index.html')

ajax携带文件数据

ajax如果想要把文件传给后端,需要利用js内置对象FormData,并且ajax需要额外指定两个参数。

前端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<input id="file" type="file">
<button id="btn">提交</button>
<script>
    $('#btn').click(function () {
        let myFormData = new FormData()
        // 对象添加文件数据
        myFormData.append('my_file', $('#file')[0].files[0])
        $.ajax({
            url: '',
            type: 'post',
            // 携带文件必须要指定的两个参数
            contentType: false,
            processData: false,
            data: myFormData,
            success: function (args) {
            }
        })
    })
</script>
</body>
</html>

后端要用request.FILES获取

def index(request):
    if request.is_ajax():
        if request.method == 'POST':
            # 获取文件信息
            print(request.FILES.get('my_file'))
    return render(request, 'index.html')

回调机制处理策略

如果使用python视图函数种其他的返回方法,比如render()、redirect()、JsonResponse(),ajax同样可以接收到。

render()和redirect()返回的是一个页面,ajax接收的数据是网页的原生代码。

JsonResponse()返回的是一个json格式数据,ajax会自动反序列化并接收。

posted @ 2022-05-19 16:53  Yume_Minami  阅读(2879)  评论(0编辑  收藏  举报