zoukankan      html  css  js  c++  java
  • Django学习-24-Ajax

    jQuery.Ajax是原生Ajax的封装,它能自动识别浏览器的Ajax对象
    HttpResponse(status='404',reason='Page Not Found')

    原生Ajax使用
    XmlHttpRequest对象的主要方法
    a. void open(String method,String url,Boolen async)
       用于创建请求
        
       参数:
           method: 请求方式(字符串类型),如:POST、GET、DELETE...
           url:    要请求的地址(字符串类型)
           async:  是否异步(布尔类型)
     
    b. void send(String body)
        用于发送请求
     
        参数:
            body: 要发送的数据(字符串类型)
     
    c. void setRequestHeader(String header,String value)
        用于设置请求头
     
        参数:
            header: 请求头的key(字符串类型)
            vlaue:  请求头的value(字符串类型)
     
    d. String getAllResponseHeaders()
        获取所有响应头
     
        返回值:
            响应头数据(字符串类型)
     
    e. String getResponseHeader(String header)
        获取响应头中指定header的值
     
        参数:
            header: 响应头的key(字符串类型)
     
        返回值:
            响应头中指定的header对应的值
     
    f. void abort()
     
        终止请求
    View Code
    XmlHttpRequest对象的主要属性:
    a. Number readyState
       状态值(整数)
     
       详细:
          0-未初始化,尚未调用open()方法;
          1-启动,调用了open()方法,未调用send()方法;
          2-发送,已经调用了send()方法,未接收到响应;
          3-接收,已经接收到部分响应数据;
          4-完成,已经接收到全部响应数据;
     
    b. Function onreadystatechange
       当readyState的值改变时自动触发执行其对应的函数(回调函数)
     
    c. String responseText
       服务器返回的数据(字符串类型)
     
    d. XmlDocument responseXML
       服务器返回的数据(Xml对象)
     
    e. Number states
       状态码(整数),如:200、404...
     
    f. String statesText
       状态文本(字符串),如:OK、NotFound...
    View Code
    function getXHR(){
        var xhr = null;
        if(XMLHttpRequest){
            xhr = new XMLHttpRequest();
        }else{
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        return xhr;
    
    }
    
    function Ajax1(){
        var xhr = getXHR();
        //var xhr = new XMLHttpRequest();
        xhr.open('POST', '/ajax_json/',true);
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                // 接收完毕
                var obj = JSON.parse(xhr.responseText);
                console.log(obj);
            }
        };
        xhr.setRequestHeader('k1','v1');
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8'); #设置请求头,指定数据压缩类型
        xhr.send("name=root;pwd=123");
    }
    jQueryAjax使用
    $.ajax({
        url:'/host',
        type:'post',
        data:{'k1':123,'k2':'abkck','ip':$.('#IP').val,'k3': JSON.stringify(dicts) },
    
        type:请求方式,GET、POST(1.9.0之后用method)
        headers:请求头
        data:要发送的数据
        contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")
        async:是否异步
        timeout:设置请求超时时间(毫秒)
        beforeSend:发送请求前执行的函数(全局)
        complete:完成之后执行的回调函数(全局)
        accepts:通过请求头发送给服务器,告诉服务器当前客户端课接受的数据类型
        dataType:将服务器端返回的数据转换成指定类型
                           "xml": 将服务器端返回的内容转换成xml格式
                          "text": 将服务器端返回的内容转换成普通文本格式
                          "html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。
                        "script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式
                          "json": 将服务器端返回的内容转换成相应的JavaScript对象
        dataType:'JSON'#如果列表中有value是列表,或字典。默认JS返回时不能处理需要添加一项关键字
        traditional:true,
        success: function(data){                        想当于回调函数
            if(data=='OK'){
                location.reload();
                location.href = '/index/'   -----> http://xxxx/index
            }
            eles{
                xxx
            }
        }
        error:function(){}            后台获取不到ajax数据时,触发
    })
    
    $.get(url="xxx",data={},success='')            和$.ajax一样,只是type=get
    $.post()
    
    Ajax后台views处理实例
    def test_ajax(request):
        ret = { 'status':True,'error':None,'data':None }
        try:
            h= request.POST.get('hostname')
            if h and len(h) > 5 :
                model.Host.objects.objects.create(
                                    hostname=h,
                        )
                else:
                ret['status'] = False
                ret['error'] = '太短了'
        except Execption as e:
            ret['status'] = False
            ret['error'] = '请求错误'
        return HttpResponse(json.dumps(ret))
    
    success处理函数
    {
            var str = JSON.parse(data)        将字符串反序列化                JSON.stringify(string)  ---->  序列化
    }
    
     小建议:Ajax数据提交,服务器和浏览器都使用字典作为数据传输,并且序列化。使用状态的时候最后定义一个状态码,分别代表不同意思
    
        *使用jQeury获取form中的标签值
                data : $('#add_form').serialize(),                form中的标签id和name字段是后台获取数据的对象名
    伪Ajax请求(利用iframe特性)
    <form action="/ajax_json/" method="POST" target="ifm1">
        <iframe id="ifm1" name="ifm1" ></iframe>
        <input type="text" name="username" />
        <input type="text" name="email" />
        <input type="submit" onclick="sumitForm();" value="Form提交"/>
    </form>
    获取iframe的response数据:
    每次iframe接收到返回的数据时,自动执行onload函数。
    function sumitForm(){
        $('#ifm1').load(function(){
            var text = $('#ifm1').contents().find('body').text();
            var obj = JSON.parse(text);
        })
    }

    文件上传实例:

    原生Ajax上传

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .upload{
                display: inline-block;padding: 10px;
                background-color: brown;
                position: absolute;
                top: 0;
                bottom: 0;
                right: 0;
                left: 0;
                z-index: 90;
            }
            .file{
                width: 100px;height: 50px;
                opacity: 0;
                position: absolute;
                top: 0;
                bottom: 0;
                right: 0;
                left: 0;
                z-index: 100;
            }
        </style>
    </head>
    <body>
        <div style="position: relative; 100px;height: 50px;">
            <input class="file" type="file" id="file" name="afafaf" />
            <a class="upload">上传</a>
        </div>
        <input type="button" value="提交XHR" onclick="xhrSubmit();" />
        <script src="/static/jquery-1.12.4.js"></script>
        <script>
            function xhrSubmit(){
                // $('#fafafa')[0]
                var file_obj = document.getElementById('fafafa').files[0];
    
                var fd = new FormData();
                fd.append('username','root');
                fd.append('file',file_obj);
    
                var xhr = new XMLHttpRequest();
                xhr.open('POST', '/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

    jQueryAjax上传

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .upload{
                display: inline-block;padding: 10px;
                background-color: brown;
                position: absolute;
                top: 0;
                bottom: 0;
                right: 0;
                left: 0;
                z-index: 90;
            }
            .file{
                width: 100px;height: 50px;
                opacity: 0;
                position: absolute;
                top: 0;
                bottom: 0;
                right: 0;
                left: 0;
                z-index: 100;
            }
        </style>
    </head>
    <body>
        <div style="position: relative; 100px;height: 50px;">
            <input class="file" type="file" id="file" name="afafaf" />
            <a class="upload">上传</a>
        </div>
        <input type="button" value="提交jQuery" onclick="jqSubmit();" />
        <script src="/static/jquery-1.12.4.js"></script>
        <script>
            function jqSubmit(){
                // $('#fafafa')[0]
                var file_obj = document.getElementById('fafafa').files[0];
    
                var fd = new FormData();
                fd.append('username','root');
                fd.append('file',file_obj);
    
                $.ajax({
                    url: '/upload_file/',
                    type: 'POST',
                    data: fd,
                    processData: false,  // tell jQuery not to process the data
                    contentType: false,  // tell jQuery not to set contentType
                    success:function(arg,a1,a2){
                        console.log(arg);  //data数据
                        console.log(a1);   //状态
                        console.log(a2);   //XML对象
                    }
                })
            }
        </script>
    </body>
    </html>
    View Code

    伪Ajax上传(按钮)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .upload{
                display: inline-block;padding: 10px;
                background-color: brown;
                position: absolute;
                top: 0;
                bottom: 0;
                right: 0;
                left: 0;
                z-index: 90;
            }
            .file{
                width: 100px;height: 50px;
                opacity: 0;
                position: absolute;
                top: 0;
                bottom: 0;
                right: 0;
                left: 0;
                z-index: 100;
            }
        </style>
    </head>
    <body>
        <div style="position: relative; 100px;height: 50px;">
            <input class="file" type="file" id="fafafa" name="afafaf" />
            <a class="upload">上传</a>
        </div>
        <form id="form1" action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1">
            <iframe id="ifm1" name="ifm1" style="display: none;"></iframe>
            <input type="submit" onclick="iframeSubmit();" value="Form提交"/>
        </form>
        <div id="preview"></div>
        <script src="/static/jquery-1.12.4.js"></script>
        <script>
            function iframeSubmit(){
                $('#ifm1').load(function(){
                    var text = $('#ifm1').contents().find('body').text();
                    var obj = JSON.parse(text);
    
                    $('#preview').empty();
                    var imgTag = document.createElement('img');
                    imgTag.src = "/" + obj.data;
                    $('#preview').append(imgTag);
                })
            }
        </script>
    </body>
    </html>
    View Code

    伪Ajax上传(自动)

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .upload{
                display: inline-block;padding: 10px;
                background-color: brown;
                position: absolute;
                top: 0;
                bottom: 0;
                right: 0;
                left: 0;
                z-index: 90;
            }
            .file{
                width: 100px;height: 50px;
                opacity: 0;
                position: absolute;
                top: 0;
                bottom: 0;
                right: 0;
                left: 0;
                z-index: 100;
            }
        </style>
    </head>
    <body>
        <div style="position: relative; 100px;height: 50px;">
            <input class="file" type="file" id="aaa" name="aaa" />
            <a class="upload">上传</a>
        </div>
        <form id="form1" action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1">
            <iframe id="ifm1" name="ifm1" style="display: none;"></iframe>
            <input type="file" name="fafafa" onchange="changeUpalod();" />
        </form>
        <div id="preview"></div>
        <script src="/static/jquery-1.12.4.js"></script>
        <script>
            function changeUpalod(){
                $('#ifm1').load(function(){
                    var text = $('#ifm1').contents().find('body').text();
                    var obj = JSON.parse(text);
                    $('#preview').empty();
                    var imgTag = document.createElement('img');
                    imgTag.src = "/" + obj.data;
                    $('#preview').append(imgTag);
                });
                $('#form1').submit();
            }
        </script>
    </body>
    </html>
    View Code

    3种Ajax使用时机
    如果发送的是【普通数据】 -> jQuery > XMLHttpRequest > iframe
    如果发送的是【文件数据】 -> iframe支持图片预览 > jQuery > XMLHttpRequest

    JSONP请求

    由于浏览器存在同源策略机制,同源策略阻止从一个源加载的文档或脚本获取或设置另一个源加载的文档的属性。

    特别的:由于同源策略是浏览器的限制,所以请求的发送和响应是可以进行,只不过浏览器不接受罢了。

    对于XMLHttpResponse和Ajax请求浏览器都会阻止

    而对于有src属性的标签不阻止

    JSONP跨域请求

    方式一:

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <p>
            <input type="button" onclick="Jsonp();"  value='提交'/>
        </p>
        <script type="text/javascript" src="jquery-1.12.4.js"></script>
        <script>
            function Jsonp(){
                var tag = document.createElement('script');
                tag.src = "http://c2.com:8000/test/";
                document.head.appendChild(tag);
                document.head.removeChild(tag);
    
            }
        </script>
    </body>
    </html>
    View Code

    方式二:

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <p>
            <input type="button" onclick="Jsonp();" value='提交'/>
        </p>
        <script type="text/javascript" src="jquery-1.12.4.js"></script>
        <script>
            function Jsonp(){
                $.ajax({
                    url: "http://c2.com:8000/test/",
                    type: 'GET',
                    dataType: 'JSONP',
                    success: function(data, statusText, xmlHttpRequest){
                        console.log(data);
                    }
                })
            }
        </script>
    </body>
    </html>
    View Code
  • 相关阅读:
    Co.
    编程
    编程
    编程
    数据同步
    Co.
    Co.
    Co.
    Co.
    sss
  • 原文地址:https://www.cnblogs.com/cq146637/p/7828633.html
Copyright © 2011-2022 走看看