Ajax

特点:异步提交,局部刷新

ajax不是一门新的技术并且有很多版本,我们目前学习的jQuery版本(版本无所谓,本质都一样)

基本语法
	$.ajax({
        url:''		填的是后端地址,三种填写方法,与form标签的action一致
        type:'post'	 请求方式,默认是get
        date:{'v1':v1Val,'v2':v2Val}  发送给后端的数据
        success:function(args){   后端返回结果之后自动触发args接收后端返回的数据
            $('#d3').val(args)
        }
    })

Ajax普通写法

实现效果:在网页两个input框输入数字,第三个input框是结果,使用Ajax调用数据还在
视图层:
    def index(request):
    if request.method == 'POST':
        v1 = request.POST.get('v1')   # 接收发过来的数据
        v2 = request.POST.get('v2')
        v3 = int(v1) + int(v2)
        return HttpResponse(v3)   # 发挥计算的结果
    return render(request, 'index.html')
模板层:
    <input type="text" id="d1"> + <input type="text" id="d2"> = <input type="text" id="d3">
<button id="subBtn">点我发送ajax</button>

<script>
    $('#subBtn').click(function () {
        let v1Val = $('#d1').val();
        console.log(v1Val)
        let v2Val = $('#d2').val();
        console.log(v2Val)
        $.ajax({
            url:'',
            type:'post',
            data:{'v1':v1Val,'v2':v2Val},
            success:function (args){
                $('#d3').val(args)}   # 在d3中添加值为返回的计算结果
        })
    })
</script>
</body>

Content-Type

1.urlencoded
	ajax默认的编码格式/form表单默认也是
    数据格式	xxx=yyy&uuu=ooo
    django后端会自动处理到requset.POST中

2.formdata
	django后端针对普通的键值对还是处理到request.POST中,但是针对文件会处理到request.FILES中
    
3.application/  发送json格式的数据
	form表单不支持 ajax可以
    	<script>
    $('#d1').click(function () {
        $.ajax({
            url:'',
            type:'post',
            data:JSON.stringify({'name':'jason','age':18}),  // 千万不要骗人家
            contentType:'application/json',
            success:function (args) {
                alert(args)
            }

        })
    })
</script>
	后端需要从request.body中获取并自己处理

ajax携带文件数据

视图层:
    def index(request):
        if request.method == 'POST':
            print(request.POST)  # <QueryDict: {'name': ['jason'], 'age': ['18']}>
            print(request.FILES)  # <MultiValueDict: {'file': [<InMemoryUploadedFile: 12.19之路由层最后一部分.md (application/octet-stream)>]}>
            name = request.POST.get('name')
            file = request.FILES.get('file')
            return HttpResponse('123')
        return render(request, 'index.html')
模板层:
    <body>
<input type="text" id="d1">
<input type="file" id="d2">

<button id="d3">携带文件数据</button>

<script>
    $('#d3').click(function () {
        // 1.先产生一个fordata对象
        let myForDataobj = new FormData();
        // 2.该对象中添加普通数据
        myForDataobj.append('name', 'jason')
        myForDataobj.append('age', 18)
        //3.往该对象中添加文件数据
        myForDataobj.append('file', $('#d2')[0].files[0])
        $.ajax({
            url: '',
            type: 'post',
            data: myForDataobj,
            // 2个固定的写法
            contentType: false,
            processData: false
        })
    })
</script>
</body>

ajax补充说明

主要是针对回调函数args接收到的响应数据

1.后端request.is_ajax()
	用于判断当前请求是否由ajax发起
2.后端返回的三板斧都会被srag接收不再影响整个浏览器页面
3.选择使用ajax做前端交互的时候,后端一般返回的都是字典数据
	user_dict = {'cod':10000,'username':'小阳人','hobby':'哎呦喂'}
    
ajax自动反序列化后端的json格式的bytes类型数据

写法;
视图层:
	def ajax_func(request):
    print(request.is_ajax())  # True
    if request.is_ajax():
        if request.method == 'POST':
            username = request.POST.get('v1')
            print(username)
            password = request.POST.get('v2')
            print(password)
            user_dict = {'code': 10000, 'username': '小阳人', 'hobby': '哎呦喂~'}
            return JsonResponse(user_dict)
    return render(request, 'ajax_func.html')

模板层:
    <body>
<p>username:
    <input type="text" id="d3"><span id="p1" style="color: red"></span>
</p>
<p>password:
    <input type="text" id="d2"><span id="p4"></span>
</p>
<button id="d1">点击</button>
<script>
    $('#d1').click(function () {
        let username = $('#d3').val()
        let password = $('#d2').val()
        $.ajax({
            url: '',
            type: 'post',
            data: {'v1': username, 'v2': password},
            success: function (args) {
                console.log(args)  # {code: 10000, username: '小阳人', hobby: '哎呦喂~'}
                console.log(args.username)  # 小阳人
            }
        })
    })
</script>
</body>
posted @ 2022-12-19 21:27  雪语  阅读(25)  评论(0)    收藏  举报