zoukankan      html  css  js  c++  java
  • Day24-part1-原生Ajax

    参考老师博客:http://www.cnblogs.com/wupeiqi/articles/5703697.html

    主要讲了:发数据的3种方式以及上传文件的3种方式。(后续需要总结)

    一,原生Ajax

    Ajax主要就是使用 【XmlHttpRequest】对象来完成请求的操作,该对象在主流浏览器中均存在(除早起的IE),Ajax首次出现IE5.5中存在(ActiveX控件)。

    JQuery提供的Ajax方法:

    $.ajax({
        url: ,
        type: '',
        dataType: '', //希望返回的是什么格式
        data: {
              
        },
        success: function(){
             
        },
        error: function(){
              
        }
     })
    

    一般来说,大家可能都会习惯用JQuery提供的Ajax方法,但是用原生的js怎么去实现Ajax方法呢?

    多么深的领悟啊啊啊!!! 

    Ajax可以实现什么样的功能呢,URL后面指的是提交到哪个网址,如果不是Ajax的话,提交到哪个网址,页面就会跳转到哪个网址。但是如果用Ajax的话,提交到某个指定的网址,但是页面还可以保持当前页面不发生变化。这就是所谓的悄悄提交。

    在URL关联的那个函数上可以做验证等一系列操作,在URL对应的页面上的返回值可以返回到Ajax中来。在Ajax中执行回调函数,进而可以显示到当前页面上来。(比如提示:字符串太长)

    Ajax的实现主要分为四部分:

    1、创建Ajax对象

    // 创建ajax对象
    var xhr = null;
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();  //// XMLHttpRequest对象用于在后台与服务器交换数据
    } else {
        //为了兼容IE6
        xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }
    

     2、连接服务器,用于创建请求

    // 连接服务器open(方法GET/POST,请求地址, 异步传输)
    xhr.open('GET',  'data.txt',  true);
    

    说明:open(method, url, async) 方法需要三个参数:

    method:(字符串类型)发送请求所使用的方法(GET或POST);与POST相比,GET更简单更快,并且在大部分情况下都能用;然而,在以下情况中,请使用POST

    • 无法使用缓存文件(更新服务器上的文件或数据库)
    • 向服务器发送大量数据(POST 没有数据量限制)
    • 发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠

    url:规定服务器端脚本的URL(该文件可以是任何类型的文件,比如 .txt 和 .xml,或服务器脚本文件,比如 .asp 和 .php (在传回响应之前,能够在服务器上执行任务)),字符串类型;

    async:规定应当对请求进行异步(true)或同步(false)处理;true是在等待服务器响应时执行其他脚本,当响应就绪后对响应进行处理;false是等待服务器响应再执行。

    既然Ajax实现的是偷偷发,那么就应该是异步的,不应该影响页面的任何效果。所以一般都用true。(布尔类型)

    3、发送请求,将请求送往服务器。

    // 发送请求
    xhr.send(String body);
    

     4、设置请求头(想往后端发数据的话,包含了请求头和请求的内容)

    // 用于设置请求头
    
    setRequestHeader(String header,String value)
    
        参数:
    
            header: 请求头的key(字符串类型)
    
            vlaue:  请求头的value(字符串类型)
    

    5、获取所有响应头

    // 获取所有响应头
    String getAllResponseHeaders()
    
        返回值:
    
            响应头数据(字符串类型)



    // 获取响应头中指定header的值
    String getResponseHeader(String header)    
     
        参数:
            header: 响应头的key(字符串类型)
     
        返回值:
            响应头中指定的header对应的值

    6、接收返回数据

    if(xhr.readyState == 4){
                success(xhr.responseText);  //获得字符串形式的响应数据。
            }

    // 处理返回数据
    /*
    ** 每当readyState改变时,就会触发onreadystatechange事件
    ** readyState属性存储有XMLHttpRequest的状态信息,存有服务器响应的状态信息。
    ** onreadystatechange:存有处理服务器响应的函数,每当(每次) readyState 改变时,onreadystatechange 函数就会被执行。 ** 0 :请求未初始化 ** 1 :服务器连接已建立 ** 2 :请求已接受 ** 3 : 请求处理中 ** 4 :请求已完成,且相应就绪 */ xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ /* ** Http状态码 ** 1xx :信息展示 ** 2xx :成功 ** 3xx :重定向 ** 4xx : 客户端错误 ** 5xx :服务器端错误 */ if(xhr.status == 200){ success(xhr.responseText); //获得字符串形式的响应数据。 } else { if(failed){ failed(xhr.status); } } } }

     5.Ajax封装函数示例:

    function Ajax(type, url, data, success, failed){
        // 创建ajax对象
        var xhr = null;
        if(window.XMLHttpRequest){
            xhr = new XMLHttpRequest();
        } else {
            xhr = new ActiveXObject('Microsoft.XMLHTTP')
        }
     
        var type = type.toUpperCase();
        // 用于清除缓存
        var random = Math.random();
     
        if(typeof data == 'object'){
            var str = '';
            for(var key in data){
                str += key+'='+data[key]+'&';
            }
            data = str.replace(/&$/, '');
        }
     
        if(type == 'GET'){
            if(data){
                xhr.open('GET', url + '?' + data, true);
            } else {
                xhr.open('GET', url + '?t=' + random, true);
            }
            xhr.send();
     
        } else if(type == 'POST'){
            xhr.open('POST', url, true);
            // 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.send(data);
        }
     
        // 处理返回数据
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                if(xhr.status == 200){
                    success(xhr.responseText);
                } else {
                    if(failed){
                        failed(xhr.status);
                    }
                }
            }
        }
    }
     
    // 测试调用
    var sendData = {name:'asher',sex:'male'};
    Ajax('get', 'data/data.html', sendData, function(data){
        console.log(data);
    }, function(error){
        console.log(error);
    });
    

      

    1、XmlHttpRequest对象介绍

    什么是 XMLHttpRequest 对象?

    XmlHttpRequest对象是浏览器的对象,不是所有的浏览器都支持的。IE6,7,8没有这个对象。所以微软有一套自己的对象。

    jQuery 1.X版本的时候,对所有的低版本浏览器也支持。(jQuery是XmlHttpRequest和微软低版本的上层封装)

    XMLHttpRequest 对象用于在后台与服务器交换数据。XMLHttpRequest 对象是开发者的梦想,因为您能够:

    • 在不重新加载页面的情况下更新网页
    • 在页面已加载后从服务器请求数据
    • 在页面已加载后从服务器接收数据
    • 在后台向服务器发送数据

    所有现代的浏览器都支持 XMLHttpRequest 对象。

    1.1 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()
    
     
    
        终止请求
    

     1.2. XMLHttprequest对象来发送原生Ajax数据的示例

    views.py

    def ajax(request):
        return render(request,'ajax.html')
    

     Ajax.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <input type="button" value="Ajax1" onclick="Ajax1();"/>
        <script>
            function Ajax1(){
                var xhr=new XMLHttpRequest(); //创建XMLHttpRequest对象
                xhr.open('GET','/index/',true); //指定用什么形式发,发到哪里,是否异步(是,默认也是true)
                xhr.send("name=root;pwd=123"); //发送的数据
            }
        </script>
    </body>
    </html>
    

     页面效果:点击Ajax1这个按钮的时候,发现页面没有变化,但是network中收到了后台发送的数据,这就是所谓的偷偷提交。

    1.3 不往Ajax页面发了,往ajax_json页面处发。问题是后台ajax函数如何收到返回的数据。

    修改程序如下

    views.py

    def ajax(request):
        return render(request,'ajax.html')
    
    def ajax_json(request):
        ret={'status':True,'data':None} #字典
        import json
        return HttpResponse(json.dumps(ret))
    

     ajax.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <input type="text"/>
        <input type="button" value="Ajax1" onclick="Ajax1();"/>
        <script>
            function Ajax1(){
                var xhr=new XMLHttpRequest(); //创建XMLHttpRequest对象
                xhr.open('GET','/ajax_json/',true); //指定用什么形式发,发到哪里,是否异步(是)
                xhr.send("name=root;pwd=123"); //发送的数据
            }
        </script>
    </body>
    </html>
    

     urls.py

    from django.conf.urls import url
    from django.contrib import admin
    from app01 import views
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^index/', views.index),
        url(r'^user_list/', views.user_list),
        url(r'^edit-(d+)/', views.user_edit),
        url(r'^ajax/$', views.ajax),
        url(r'^ajax_json/$', views.ajax_json),
        url(r'^orm/', views.orm),
    ]
    

     访问页面,发现chrome拿到了ajax_json函数的返回值。

    现在想把返回值打印到当前页面上,比如:字符串太长。

    首先需要在Ajax函数中写一个回调函数。

    1.4 XmlHttpRequest对象的主要属性,调用属性的时候不需要加括号:

    a. Number readyState
    
       状态值(整数)
    
     
    
       详细:
    
          0-未初始化,尚未调用open()方法;
    
          1-启动,调用了open()方法,未调用send()方法;
    
          2-发送,已经调用了send()方法,未接收到响应;
    
          3-接收,已经接收到部分响应数据;
    
          4-完成,已经接收到全部响应数据;
    
     
    
    b. Function onreadystatechange  #回调函数
    
       当readyState的值改变时自动触发执行其对应的函数(回调函数)
    
     
    
    c. String responseText
    
       服务器返回的数据(字符串类型)
    
     
    
    d. XmlDocument responseXML 实质上还是文本,如果返回的是XML对象,在内部XMLHttprequest对象就可以帮我们完成这件事情(把text转换成xml格式的对象)。咱们一般用的都是json
    
       服务器返回的数据(Xml对象)
    
     
    
    e. Number states
    
       服务端返回的状态码(整数),如:200、404...
    
     
    
    f. String statesText
    
       每个状态码都对应一个状态文本(字符串),如:OK(200)、NotFound(404)...
    

     1.5 在前端页面上拿到返回值。

    ajax.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <input type="text"/>
        <input type="button" value="Ajax1" onclick="Ajax1();"/>
        <script>
            function Ajax1(){
                var xhr=new XMLHttpRequest(); //创建XMLHttpRequest对象
                xhr.open('GET','/ajax_json/',true); //指定用什么形式发,发到哪里,是否异步(是)
                xhr.onreadystatechange=function(){
                    if(xhr.readyState==4){
                        //接收完毕,放到XMLHttprequest对象里面了,我们可以去取了。
                        console.log(xhr.responseText); //这就是我们要拿的返回值
                    }
                };
                xhr.send("name=root;pwd=123"); //发送的数据
            }
        </script>
    </body>
    </html>
    

     1.6 返回状态码以及状态码对应的内容。这样拿到数据后就能直接知道错误原因了。如果只返回'status':False的话,则表示得不明确,不知道具体的错误在哪里。

    def ajax(request):
        return render(request,'ajax.html')
    
    def ajax_json(request):
        ret={'status':True,'data':None} #字典
        import json
        return HttpResponse(json.dumps(ret),status=404,reason='Not Found')
    

    1.7 代码保存,发送GET请求

    ajax.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <input type="text"/>
        <input type="button" value="Ajax1" onclick="Ajax1();"/>
        <script>
            function Ajax1(){
                var xhr=new XMLHttpRequest(); //创建XMLHttpRequest对象
                xhr.open('POST','/ajax_json/',true); //指定用什么形式发,发到哪里,是否异步(是)
                xhr.onreadystatechange=function(){
                    if(xhr.readyState==4){
                        //接收完毕,放到XMLHttprequest对象里面了
                        var obj=JSON.parse(xhr.responseText);
                        console.log(obj);
                    }
                };
                
            xhr.setRequestHeader('k1','v1'); //发送的时候带着请求头,csrf的时候用。 //xhr.send("name=root;pwd=123"); //发送的数据 } </script> </body> </html>

     views.py

    def ajax(request):
        return render(request,'ajax.html')
    
    def ajax_json(request):
        ret={'status':True,'data':None} #字典
        import json
        return HttpResponse(json.dumps(ret),status=404,reason='Not Found')
    

    1.8 用原生的Ajax发送POST请求:一定要记住需要设置请求头。

    xhr.send("name=root;pwd=123"); //发送的数据,把这种格式的数据发送给后台,后台不知道该怎么解析。相当于jquery_ajax中的data

    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8'); //所以一定要切记加上请求头,

    xhr.setRequestHeader('k1','v1'); //发送的时候带着请求头,csrf token的时候用。

    POST请求的时候需要带着CSRF token,可以获取到这个值直接写到内容中,也可以写到请求头中。(利用setRequestHeader)

    views.py

    def ajax(request):
        return render(request,'ajax.html')
    
    def ajax_json(request):
        print(request.POST)
        ret={'status':True,'data':None} #字典
        import json
        return HttpResponse(json.dumps(ret),status=404,reason='Not Found')
    

    Ajax.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <input type="text"/>
        <input type="button" value="Ajax1" onclick="Ajax1();"/>
        <script>
            function Ajax1(){
                var xhr=new XMLHttpRequest(); //创建XMLHttpRequest对象
                xhr.open('POST','/ajax_json/',true); //指定用什么形式发,发到哪里,是否异步(是)
                xhr.onreadystatechange=function(){
                    if(xhr.readyState==4){
                        //接收完毕,放到XMLHttprequest对象里面了
                        var obj=JSON.parse(xhr.responseText);
                        console.log(obj);
                    }
                };
                xhr.setRequestHeader('k1','v1'); //发送的时候带着请求头,csrf的时候用。
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
                //设置请求头,判断发来的请求头里面,怎么样把数据打包的。这样后台就知道怎么样去解了。
                xhr.send("name=root;pwd=123"); //发送的数据
            }
        </script>
    </body>
    </html>
    

    效果:

    1.9, 浏览器的兼容性问题

    var xhr=new XMLHttpRequest(); //创建XMLHttpRequest对象
    var xhr=new ActiveXObject('Microsoft.XMLHTTP'); //兼容旧版本


    1.10 版本兼容

    Ajax.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <input type="text"/>
        <input type="button" value="Ajax1" onclick="Ajax1();"/>
        <script>
            function getXHR(){
                var xhr = null;
                if(XMLHttpRequest){
                    xhr = new XMLHttpRequest();
                }else{
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                }
                return xhr;
    
            }
    
            function Ajax1(){
                //var xhr=new XMLHttpRequest(); //创建XMLHttpRequest对象
                var xhr=getXHR(); //为了兼容IE旧版本
                xhr.open('POST','/ajax_json/',true); //指定用什么形式发,发到哪里,是否异步(是)
                xhr.onreadystatechange=function(){
                    if(xhr.readyState==4){
                        //接收完毕,放到XMLHttprequest对象里面了
                        var obj=JSON.parse(xhr.responseText);
                        console.log(obj); //这就是我们要拿的返回值
                    }
                };
                xhr.setRequestHeader('k1','v1'); //发送的时候带着请求头,csrf的时候用。
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
                //设置请求头,判断发来的请求头里面,怎么样把数据打包的。这样后台就知道怎么样去解了。
                xhr.send("name=root;pwd=123"); //发送的数据
            }
    
    
            $.ajax({
                success:function(arg,a1)
            })
        </script>
    </body>
    </html>
    

     

    二,jQuery的Ajax

    $.ajax({
        url: ,
        type: '',
        dataType: '', //希望返回的是什么格式
        data: {
              
        },
        success: function(){
             
        },
        error: function(){
              
        }
     })
    

    success: 中可以有个参数xmlHttpRequest,里面包含了所有的内容。所以我们可以用arg返回所需要的值,也可以用原生的xmlHttpRequest 的来获取。

            $.ajax({
                success:function(arg,a1,xmlHttpRequest)
            })
    
  • 相关阅读:
    均匀分布
    吉布斯采样(Gibbs采样)
    蒙特卡罗方法 Monte Carlo method
    马尔科夫链
    python 3 没有了xrange
    %matplotlib inline的含义
    MCMC采样和M-H采样
    pycharm 安装模块 use the correct version of 'pip' installed for your Python interpreter
    Pycharm安装第三方库时出现Read timed out的解决办法
    如何在Pycharm中添加新的模块(第三方包)
  • 原文地址:https://www.cnblogs.com/momo8238/p/7763556.html
Copyright © 2011-2022 走看看