zoukankan      html  css  js  c++  java
  • django学习之- Ajax

    提示:jquery要使用1版本,因为高版本已不兼容低版本的游览器。
    参考url:http://www.cnblogs.com/wupeiqi/articles/5703697.html
    原生ajax:Ajax主要就是使用 【XmlHttpRequest】对象来完成请求的操作,该对象在主流浏览器中均存在(除早起的IE),Ajax首次出现IE5.5中存在(ActiveX控件)。
    XmlHttpRequest对象的主要方法:
     1 a. void open(String method,String url,Boolen async)
     2    用于创建请求
     3     
     4    参数:
     5        method: 请求方式(字符串类型),如:POST、GET、DELETE...
     6        url:    要请求的地址(字符串类型)
     7        async:  是否异步(布尔类型)
     8  
     9 b. void send(String body)
    10     用于发送请求
    11  
    12     参数:
    13         body: 要发送的数据(字符串类型)
    14  
    15 c. void setRequestHeader(String header,String value)
    16     用于设置请求头
    17  
    18     参数:
    19         header: 请求头的key(字符串类型)
    20         vlaue:  请求头的value(字符串类型)
    21  
    22 d. String getAllResponseHeaders()
    23     获取所有响应头
    24  
    25     返回值:
    26         响应头数据(字符串类型)
    27  
    28 e. String getResponseHeader(String header)
    29     获取响应头中指定header的值
    30  
    31     参数:
    32         header: 响应头的key(字符串类型)
    33  
    34     返回值:
    35         响应头中指定的header对应的值
    36  
    37 f. void abort()
    38  
    39     终止请求
    View Code

    XmlHttpRequest对象的主要属性:

     1 a. Number readyState
     2    状态值(整数)
     3  
     4    详细:
     5       0-未初始化,尚未调用open()方法;
     6       1-启动,调用了open()方法,未调用send()方法;
     7       2-发送,已经调用了send()方法,未接收到响应;
     8       3-接收,已经接收到部分响应数据;
     9       4-完成,已经接收到全部响应数据;
    10  
    11 b. Function onreadystatechange
    12    当readyState的值改变时自动触发执行其对应的函数(回调函数)
    13  
    14 c. String responseText
    15    服务器返回的数据(字符串类型)
    16  
    17 d. XmlDocument responseXML
    18    服务器返回的数据(Xml对象)
    19  
    20 e. Number states
    21    状态码(整数),如:200、404...
    22  
    23 f. String statesText
    24    状态文本(字符串),如:OK、NotFound...
    View Code

    实例:

    前台代码

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <title>ajax</title>
     6 </head>
     7 <body>
     8     <p>
     9         <input name="test" />
    10         <input type="button" value="Ajax1" onclick="Ajax1()" />
    11     </p>
    12     <script>
    13         function getXHR() {
    14 {#            游览器兼容#}
    15             var xhr = null;
    16             if(XMLHttpRequest){
    17                 {#            新建#}
    18                 var xhr = new XMLHttpRequest();
    19             }else{
    20                 xhr = new ActiveXObject("Microsoft.XMLHTTP");
    21             }
    22         }
    23         function Ajax1() {
    24 {#            打开#}
    25             xhr.open('POST','/app04/ajax_json',true);
    26             xhr.onreadystatechange =function () {
    27 {#                onreadystatechange是readyState的回调函数,判断值为多少的时候执行什么动作#}
    28                 if(xhr.readyState == 4){
    29                     //表示接收完毕,以下打印返回值
    30                     var obj = JSON.parse(xhr.responseText);
    31                     console.log(obj);
    32                 }
    33             };
    34 {#            发请求时候额外带个头写法,CSRF可使用#}
    35             xhr.setRequestHeader('k1','v1');
    36             //django的post源码里已指定固定格式,否则后端无法收到数据
    37             xhr.setRequestHeader('content-type','application/x-www-form-urlencoded; charset-UTF-8');
    38             {#            发送,send发送格式固定#}
    39             xhr.send('name=root;pwd=123');
    40         }
    41     </script>
    42 </body>
    43 </html>
    View Code

    后台代码

    1 def ajax(request):
    2     return render(request,'app04/ajax.html')
    3 
    4 def ajax_json(request):
    5     print(request.POST)
    6     ret = {'code':True,'data':None}
    7     import json
    8     return HttpResponse(json.dumps(ret))
    View Code

    路由代码

    1     url(r'^ajax$',views.ajax),
    2     url(r'^ajax_json',views.ajax_json),
    View Code

     Ajax写法格式解释

    $.Ajax({          # 提交到后台
        url:'/host', # 提交到哪里
        type:'POST' # 提交方式
        # 第一种写法
        data:{'k1':123,'k2':'root'} # 提交数据
        # 第二种写法
        data:$('#add_form').serialize(), #代替上一句,将form表单里所有数据统一打包发到后台
        # 注意如果data字典中还包含1个字典,这个包含的字典需要转为字符串才可以发送:JSON.stringfy({'k1','v1'})
        dataType:'JSON',    # 这里是jquery功能,将传回来的数据进行json解析,就不需要下面的函数再次进行解析了,下面函数中的参数就为obj对象
        traditional:true,   # 可以将data中的列表数据传到后台,python使用get_list来接收列表数据。
        success: function(data){  # 回调函数,等待接收上面提交后的返回数据
            // data是服务器端返回的字符串
            var obj = JSON.parse(data);
        }
        error:function(){ #当前台发送了一个请求到后台,后台未捕捉到发了个未知的错误,才触发这里执行
        }
    })
    建议:永远让服务端返回一个字典,返回方式:return HttpResponse(json.dumps(字典))
    不要使用render,因为返回的模板文件只做渲染,无法json转换,不支持redirect方法。
    以下这些方法全部是调用上面的Ajax方法,不同的是只修改对应的type方法,所以说只用Ajax方法即可。
    $.get(url='XX',data:{},success)
    $.post
    - 跨域请求(jsonp,CORS)
    - ajax上传文件(2种方式)
    伪造ajax请求代码
    <form action="/app02/ajax_json" method="post" target="ifm"> # target=ifm使form和iframe建立管理
    <iframe name="ifm"></iframe> #通过iframe绑定form后进行在页面不刷新的情况下提交
    <input type="text" name="uname" />
    <input type="text" name="email" />
    <input type="submit" value="form提交" />
    </form>
    时机:
    如果发送的是普通数据,使用顺序优先级:jquery,XMLHttpRequest,iframe

    获取iframe标签的内容
    function submitForm() {
    $('#ifm').load(function () {
    var ifmcontent = $('#ifm').contents().find('body').text()
    console.log(JSON.parse(ifmcontent))
    })
    }
    实例:上传文件
    前端的3种写法
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <input type="file" id="fafafa" name="fafafa"/>
    <a>上传</a>
    <input type="button" value="提交XHR" onclick="xhrSubmit()">
    <input type="button" value="提交XHR" onclick="ajaxSubmit()">
    
    <form id='fm1' enctype="multipart/form-data" action="/app02/upload_file/" method="post" target="ifm">
        <iframe id='ifm' name="ifm"></iframe>
        <input type="file" name="fafafa" onchange="changeUpload();"/>
        <input type="submit" onclick="iframeSubmit();" value="form提交"/>
    </form>
    <div id="preview"></div>
    <script src="/static/jquery-1.12.4.min.js"></script>
    <script>
        function changeUpload() {
    {#        输入框改变自动执行,提交操作#}
            $('#fm1').submit()
            iframeSubmit()
        }
        function iframeSubmit() {
            $('#ifm').load(function () {
                var ifmcontent = $('#ifm').contents().find('body').text();
                var obj = JSON.parse(ifmcontent);
                $('#preview').empty();
                var tagimg = document.createElement('img');
                tagimg.src = '/' + obj.data;
                $('#preview').append(tagimg)
            })
        }
        function ajaxSubmit() {
            var file_obj = document.getElementById('fafafa').files[0];
            var fd = new FormData();
            fd.append('uname','afafaf');
            fd.append('fafafa',file_obj);
            $.ajax({
                url:'/app02/upload_file/',
                type:'POST',
                data:fd,
                processData:false,
                contentType:false,
                success:function (arg,a1,a2) {
                    console.log(arg)
                    console.log(a1)
                    console.log(a2)
                }
            })
        }
        function xhrSubmit() {
            var file_obj = document.getElementById('fafafa').files[0];
            console.log(file_obj);
            var fd = new FormData();
            fd.append('uname','afafaf');
            fd.append('fafafa',file_obj);
            var xhr = new XMLHttpRequest();
            xhr.open('POST','/app02/upload_file/',true);
            xhr.onreadystatechange = function () {
                if(xhr.readyState == 4){
                    var obj = JSON.parse(xhr.responseText);
                    console.log(obj)
                }
            };
            xhr.send(fd)
        }
    </script>
    </body>
    </html>
    View Code

    views的写法

    def upload(request):
        if request.method == 'GET':
            return render(request,'app02/upload.html')
    def upload_file(request): # 上传文件
        uname = request.POST.get('uname')
        fff = request.FILES.get('fafafa')
        import os
        upfile = os.path.join('static/img',fff.name)
        f = open(upfile,'wb')
        for d in fff.chunks():
            f.write(d)
        f.close()
        ret = {'code': True, 'data': upfile}
        import json
        return HttpResponse(json.dumps(ret))
    
    def upload_img(request): # 上传图片
        request.GET.get('dir') # 这个方法可获取显示上传文件的类型
        obj = request.FILES.get('imgFile')
        import os
        upfile = os.path.join('static/img',obj.name)
        f = open(upfile,'wb')
        for d in obj.chunks():
            f.write(d)
        f.close()
        import json
        dic = {
            'error':0,
            'url':'/'+upfile,
            'message':'error'
        }
        return HttpResponse(json.dumps(dic))
    View Code
  • 相关阅读:
    Python 购物车程序(文件版)
    Python 购物车程序
    Python多级菜单显示和登录小接口
    ARM体系结构与编程-第五章
    ARM体系结构与编程-第四章
    ARM的IRQ模式和FIQ模式
    C结构体的初始化和赋值
    ARM体系结构与编程-第三章
    函数调用过程分析
    关于STM32-M3/M4的MSP和PSP
  • 原文地址:https://www.cnblogs.com/zy6103/p/8128436.html
Copyright © 2011-2022 走看看