day69

今日回顾

Django与Ajax

一、什么是Ajax

AJAX(Asynchronous Javascript And XML)翻译成中文就是"异步Javascript和XML"。即使用Javascript语言与服务器进行异步交互,传输的数据为XML(当然,传输的数据不只是XML,现在更多使用json数据)。

  • 同步交互:客户端发出一个请求后,需要等待服务器响应结束后,才能发出第二个请求;
  • 异步交互:客户端发出一个请求后,无需等待服务器响应结束,就可以发出第二个请求。

AJAX除了异步 的特点外,还有一个就是:浏览器页面局部刷新;(这一特点给用户的感受是在不知不觉中完成请求和响应过程)

优点:Ajax使用Javascript技术向服务器发送请求,Ajax无须刷新整个页面

使用:使用了jq帮咱们封装的方法 ajax ,名字跟ajax相同 $.ajax

真正的ajax原生,需要使用js操作,jq的ajax方法是对原生js的封装,方便咱们使用

-前后端混合项目中,我们通常使用jq的ajax实现 js和后端异步交互

-jq操作dom

-jq发ajax请求

-前后端分离项目中,我们会使用另一个第三方库,实现 js和后端异步交互(axios)

-只想发送ajax请求---》只用来发ajax请求的库

二、基于jquery的Ajax实现

html 复制代码
<button class="send_Ajax">send_Ajax</button>
<script>

       $(".send_Ajax").click(function(){

           $.ajax({
               url:"/handle_Ajax/",
               type:"POST",
               data:{username:"Yuan",password:123},
               success:function(data){
                   console.log(data)
               },
               
               error: function (jqXHR, textStatus, err) {
                        console.log(arguments);
                    },

               complete: function (jqXHR, textStatus) {
                        console.log(textStatus);
                },

               statusCode: {
                    '403': function (jqXHR, textStatus, err) {
                          console.log(arguments);
                     },

                    '400': function (jqXHR, textStatus, err) {
                        console.log(arguments);
                    }
                }

           })

       })

</script>

三、案例

通过Ajax,实现前端输入两个数字,服务器做加法,返回到前端页面

html 复制代码
<h1>写一个计算小案例--ajax</h1>
<input type="text" name="one" id="one"> + <input type="text" name="two" id="two"> = <input type="text" name="three"
                                                                                           id="three">
<button id="id_btn">计算</button>

<script>
    $("#id_btn").click(function () {
        //alert('xxx')
        // 取出前两个输入框的值
        var one = $("#one").val()
        var two = $("#two").val()
        //向后端发送请求
        $.ajax({
            url: '/demo01/',
            method: 'post',
            data: {one: one, two: two},
            success: function (res) {
                console.log(typeof res)
                if (res.code == 100) {
                    $("#three").val(res.result)
                } else {
                    alert(res.msg)
                }
            }
        })
    })
python 复制代码
def demo01(request):
    if request.method == 'GET':
        return render(request, 'demo01.html')
    else:
        one = int(request.POST.get('one'))
        two = int(request.POST.get('two'))
        return JsonResponse({'code': 100, 'msg': '计算成功','result:one + two })        

四、文件上传

html 复制代码
<h1>文件上传</h1>
<input type="file" id="id_file">
<button id="id_submit">上传文件</button>

<script>
    $("#id_submit").click(function () {

            var formdata = new FormData()
        // $("#id_file")[0].files[0]
        // $("#id_file") 根据id拿到标签---》jq把标签放到一个 列表中  ,
        // 取 第 0个位置,是取出第一个符合条件【id为id_file】的标签,想拿文件--》标签对象.files--->对象---》从对象中取出 key 为 0 对应的文件对象

            formdata.append('myfile', $("#id_file")[0].files[0])
            $.ajax({
                url: '/demo01/',
                method: 'post',
            // 指定编码,上传文件
                processData: false,  //默认会预处理数据---》把 {one: one, two: two}---》转成  one=1&two=2
                contentType: false,  //默认是urlencoded---》不指定编码---》上传文件必须要用 form-data
                data: formdata,
                success: function (res) {
                    if (res.code == 100) {
                        alert(res.msg)
                }     else {
                        alert(res.msg)
                }
            }
        })
    })
</script>
python 复制代码
def demo01(request):
    if request.method == 'GET':
        return render(request, 'demo01.html')
    else:
        one = int(request.POST.get('one'))
        two = int(request.POST.get('two'))
        myfile = request.FILES.get('myfile')
        with open(myfile.name, 'wb') as f:
            for line in myfile:
                f.write(line)

        print(request.body)

        return JsonResponse({'code': 100, 'msg': '上传成功', })

五、Ajax提交json数据格式

html 复制代码
<script>
$("#ajax_test").click(function () {
    var dic={'name':'lqz','age':18}
    $.ajax({
        url:'',
        type:'post',
        contentType:'application/json',  //一定要指定格式 contentType: 'application/json;charset=utf-8',
        data:JSON.stringify(dic),    //转换成json字符串格式
        success:function (data) {
            console.log(data)
        }

    })

})
</script>

提交到服务器的数据都在 request.body 里,取出来自行处理

相关推荐
高洁012 小时前
智能博弈背景下中国AI国防建设的战略价值
人工智能·python·深度学习·django·tornado
FYKJ_20103 小时前
django个性化新闻推荐35173-计算机课程设计、毕业设计
java·spring boot·后端·python·架构·django·课程设计
毕业设计7036 小时前
(免费领源码)django空气净化器销售系统09218- java、PHP、python、C#、小程序、大数据、单片机、网络工程等)
python·scrapy·mysql·pycharm·django·flask·pandas
VidDown1 天前
上传 2GB 文件别让 Django 接:分片上传、对象存储直传与秒传
python·django·音视频·状态模式·实时音视频·视频编解码·视频
菜鸟变凤凰20232 天前
基于深度学习 YOLOv8 的各种识别系统(Vue3 + Element Plus + Django 全栈项目)
深度学习·yolo·django
专业程序开发源2 天前
django便利店外卖后台管理系统19650-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·django·课程设计
vx_Biye_Design2 天前
springboot旅游管理系统18006-计算机课程设计、毕业设计
java·spring boot·后端·python·elasticsearch·django·课程设计
汉吉龙测控技术3 天前
多模态数据融合驱动的智能监测实验台
django
wangchunyu1143 天前
食韵味简 —— 免费开源的中式菜谱 API 服务
python·django·开源
专业程序开发源3 天前
SSM笔记本在线销售系统32649-计算机课程设计、毕业设计
java·spring boot·后端·python·django·php·课程设计