• 3-Vue-通过axios实现数据请求、json数据的语法、同源策略


     今日内容

    • 4. 通过axios实现数据请求
      • 4.1 json4.1.1 json数据的语法
        • 4.1.2 js中提供的json数据转换方法
      • 4.2 ajax4.2.1 数据接口
        • 4.2.3 ajax的使用
        • 4.2.4 同源策略
        • 4.2.5 ajax跨域(跨源)方案之CORS

     今日内容详细

    4. 通过axios实现数据请求

    vue.js默认没有提供ajax功能的。

    所以使用vue的时候,一般都会使用axios的插件来实现ajax与后端服务器的数据交互。

    注意,axios本质上就是javascript的ajax封装,所以会被同源策略限制。

    下载地址:

    https://unpkg.com/axios@0.18.0/dist/axios.js
    https://unpkg.com/axios@0.18.0/dist/axios.min.js

    使用文档:https://www.kancloud.cn/yunye/axios/234845

    axios提供发送http请求的常用方法有两个:axios.get() 和 axios.post() 。

    增 post

    删 delete

    改 put/patch

    查 get

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="vue.js"></script>
        <script src="axios.js"></script>
    </head>
    <body>
    <div id="app"></div>
    <script>
        var vm = new Vue({
            el:"#app",
            data:{},
            // 在初始化的时候自动发送ajax获取数据
            created(){
                axios.get("http://wthrcdn.etouch.cn/weather_mini?city=北京")
                .then(response=>{
                    console.log("http请求成功")
                    console.log(response); // http响应对象
                    console.log(response.data); // 返回的数据
                })
                .catch(error=>{
                    // 请求失败或者then里面代码出现错误时
                    console.log("http请求失败或者then里面代码报错");
                    console.log(error);
                    console.log(error.response.data); // 如果希望获取来自服务器的错误信息
                });
            }
        });
    </script>
    </body>
    </html>
    // 发送get请求
        // 参数1: 必填,字符串,请求的数据接口的url地址,例如请求地址:http://www.baidu.com?id=200
        // 参数2:可选,请求参数和请求头内容,json对象,要提供给数据接口的参数
        axios.get('服务器的资源地址',{ // http://www.baidu.com
            params:{
                参数名:'参数值', // id: 200,
            },
            headers:{
                选项名:'选项值', // 请求头
            }
        
        }).then(response=>{ // 请求成功以后的回调函数
                console.log("请求成功");
                console.log(response.data); // 获取服务端提供的数据
        
        }).catch(error=>{   // 请求失败以后的回调函数
                console.log("请求失败");
                console.log(error.response);  // 获取错误信息
        });
    
        // 发送post请求,参数和使用和axios.get()类似。
        // 参数1: 必填,字符串,请求的数据接口的url地址
        // 参数2:必填,json对象,要提供给数据接口的参数,如果没有参数,则必须使用{}
        // 参数3:可选,json对象,请求头信息
        axios.post('服务器的资源地址',{
            username: 'xiaoming',
            password: '123456'
        },{
            headers:{
                选项名:"选项值",
            }
        })
        .then(response=>{ // 请求成功以后的回调函数
          console.log(response);
        })
        .catch(error=>{   // 请求失败以后的回调函数
          console.log(error);
        });
    
        
        // b'firstName=Fred&lastName=Flintstone'

    注意:

    axios.delete() 的用法和参数与axios.get()一样,
    
    axios.put()或者axios.patch的用法和参数与axios.post()一样。
    
    在http协议中,不同的请求动作都有不同的含义,例如:
    
    get 代表向目标服务器请求获取数据
    
    post 代表向目标服务器请求上传数据
    
    put 代表向目标服务器请求更新数据【修改全部数据】
    
    patch 代表向目标服务器请求更新数据【修改部分数据】
    
    patch 代表向目标服务器请求更新数据
    
    delete 代表向目标服务器请求删除数据

    4.1 json

    json是 JavaScript Object Notation 的首字母缩写,单词的意思是javascript对象表示法,这里说的json指的是类似于javascript对象的一种数据格式。

    json的作用:在不同的系统平台,或不同编程语言之间传递数据。

    4.1.1 json数据的语法

    json数据对象类似于JavaScript中的对象,但是它的键对应的值里面是没有函数方法的,值可以是普通变量,不支持undefined,值还可以是数组或者json对象。

    // 原生的js的json对象
    var obj = {
      age:10,
      sex: '女',
      work(){                     // work: function(){}的简写
        return "好好学习",
      },
    }
    // json数据的对象格式,json数据格式,是没有方法的,只有属性,属性值:字符串,数值(整数,浮点数,布尔值), json,
    {
        "name":"tom",
        "age":18
    }
    
    // json数据的数组格式:
    ["tom",18,"programmer"]

    复杂的json格式数据可以包含对象和数组的写法。

    {
      "name":"小明",
      "age":200,
      "is_delete": false,
      "fav":["code","eat","swim","read"],
      "son":{
        "name":"小小明",
        "age":100,
        "lve":["code","eat"]
      }
    }
    
    // 数组结构也可以作为json传输数据。

    json数据可以保存在.json文件中,一般里面就只有一个json对象。

    总结:

    1. json文件的后缀是.json
    2. json文件一般保存一个单一的json数据
    3. json数据的属性不能是方法或者undefined,属性值只能:数值[整数,小数,布尔值]、字符串、json和数组
    4. json数据只使用双引号、每一个属性成员之间使用逗号隔开,并且最后一个成员没有逗号。
       {
          "name":"小明",
          "age":200,
          "fav":["code","eat","swim","read"],
          "son":{
            "name":"小小明",
            "age":100
          }
        }

    工具postman可以用于测试开发的数据接口。

    postman就是一个软件,专门提供给开发者组织和测试http请求的。

     

    4.1.2 js中提供的json数据转换方法

    javascript提供了一个JSON对象来操作json数据的数据转换.

    方法参数返回值描述
    stringify json对象 字符串 json对象转成字符串
    parse 字符串 json对象 字符串格式的json数据转成json对象

     

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <script>
        // json语法
        let humen = {
            "username":"xiaohui",
            "password":"1234567",
            "age":20
        };
    
        console.log(humen);
        console.log(typeof humen);
    
        // JSON对象提供对json格式数据的转换功能
        // stringify(json对象)  # 用于把json转换成字符串
        let result = JSON.stringify(humen);
        console.log(result);
        console.log(typeof result);
    
        // parse(字符串类型的json数据)  # 用于把字符串转成json对象
        let json_str = '{"password":"1123","age":20,"name":"xiaobai"}';
        console.log(json_str)
        console.log(typeof json_str)
    
        let json_obj = JSON.parse(json_str);
        console.log(json_obj);
        console.log(typeof json_obj)
    
        console.log(json_obj.age)
    </script>
    </body>
    </html>

    4.2 ajax

    ajax,一般中文称之为:"阿贾克斯",是英文 “Async Javascript And Xml”的简写,译作:异步js和xml数据传输数据。

    ajax的作用: ajax可以让js代替浏览器向后端程序发送http请求,与后端通信,在用户不知道的情况下操作数据和信息,从而实现页面局部刷新数据/无刷新更新数据。

    所以web开发中ajax是很常用的技术,主要用于操作后端提供的数据接口,从而实现网站的前后端分离

    ajax技术的原理是实例化js的XMLHttpRequest对象,使用此对象提供的内置方法就可以与后端进行数据通信。

    实际而言,axios或者jQuery提供的ajax,本质上就是XMLHttpRequest对象操作的封装。

    4.2.1 数据接口

    数据接口,也叫api接口,表示后端提供操作数据/功能的url地址给客户端使用。

    客户端通过发起请求向服务端提供的url地址申请操作数据【操作一般:增删查改】

    同时在工作中,大部分数据接口都不是手写,而是通过函数库/框架来生成。

     

    4.2.3 ajax的使用

    ajax的使用必须与服务端程序配合使用,但是目前我们先学习ajax的使用,所以暂时先不涉及到服务端python代码的编写。因此,我们可以使用别人写好的数据接口进行调用。

    jQuery将ajax封装成了一个函数$.ajax(),我们可以直接用这个函数来执行ajax请求。

    接口地址
    天气接口 http://wthrcdn.etouch.cn/weather_mini?city=城市名称
    音乐接口搜索 http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=歌曲标题
    音乐信息接口 http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.song.play&songid=音乐ID

     

    编写代码获取接口提供的数据:

    jQ版本

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="js/jquery-1.12.4.js"></script>
        <script>
        $(function(){
            $("#btn").on("click",function(){
                $.ajax({
                    // 后端程序的url地址
                    url: 'http://wthrcdn.etouch.cn/weather_mini',
                    // 也可以使用method,提交数据的方式,默认是'GET',常用的还有'POST'
                    type: 'get', 
                    dataType: 'json',  // 返回的数据格式,常用的有是'json','html',"jsonp"
                    data:{ // 设置发送给服务器的数据,如果是get请求,也可以写在url地址的?后面
                        "city":'北京'
                    }
                })
                .done(function(resp) {     // 请求成功以后的操作
                    console.log(resp);
                })
                .fail(function(error) {    // 请求失败以后的操作
                    console.log(error);
                });
            });
        })
        </script>
    </head>
    <body>
    <button id="btn">点击获取数据</button>
    </body>
    </html>

    Vue版本

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="js/vue.js"></script>
        <script src="js/axios.js"></script>
    </head>
    <body>
        <div id="app">
            <input type="text" v-model="city">
            <button @click="get_weather">点击获取天气</button>
        </div>
        <script>
            let vm = new Vue({
                el:"#app",
                data:{
                    city:"",
                },
                methods:{
                    get_weather(){
                        // http://wthrcdn.etouch.cn/weather_mini?city=城市名称
                        axios.get("http://wthrcdn.etouch.cn/weather_mini?city="+this.city)
                            .then(response=>{
                                console.log(response);
    
                            }).catch(error=>{
                                console.log(error.response)
                        });
                      // 上面的参数写法,也可以是下面这种格式:
                      // axios.get("http://wthrcdn.etouch.cn/weather_mini",{
                      //     // get请求的附带参数
                      //     params:{
                      //         "city":"广州",
                      //     }
                      // }).then(response=>{
                      //     console.log(response.data);  // 获取接口数据
                      // }).catch(error=>{
                      //     console.log(error.response); // 获取错误信息
                      // })
                    }
                }
            })
        </script>
    </body>
    </html>

    XMLHttpRequest的基本演示

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="vue.js"></script>
        <script src="axios.js"></script>
    </head>
    <body>
    <div id="app"></div>
    <script>
        // XMLHttpRequest的使用有4个步骤
        // 1. 实例化XMLHttpRequest
        var xhr = new XMLHttpRequest(); // 得到ajax对象
        // 2. 创建http请求
        // 参数1: 字符串,http请求动作,一般是get,post
        // 参数2: 字符串,请求的服务端的url地址
        xhr.open("get","http://wthrcdn.etouch.cn/weather_mini?city=北京")
    
        // 3. 发送请求
        // 参数1:字符串,当post请求有请求体数据,则需要把数据填写到这里
        // 例如:xhr.send("name=xiaoming&age=17")
        xhr.send()
    
        // 4. 获取服务端响应数据
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                // xhr.readyState表示xhr的状态码,1表示ajx对象刚创建,2表示ajax请求组装完成,3表示ajax请求已发送到服务端,4表示客户端已经获取到服务端返回的数据结果
                if(xhr.status == 200){
                    // xhr.status http响应状态码
                    data = JSON.parse(xhr.responseText);
                    console.log( data );
                }
            }
        }
    </script>
    </body>
    </html>

    4.2.4 同源策略

    同源策略,是浏览器为了保护用户信息安全的一种安全机制。所谓的同源就是指代通信的两个地址(例如服务端接口地址与浏览器客户端页面地址)之间比较,是否协议、域名(IP)和端口相同。不同源的客户端脚本[javascript]在没有得到服务端的明确授权的情况下,浏览器会拒绝显示服务端信息提供给前端ajax。

    ajax本质上还是javascript,是运行在浏览器中的脚本语言,所以会被受到浏览器的同源策略所限制。

    前端地址:http://www.oldboy.cn/index.html是否同源原因
    http://www.oldboy.cn/user/login.html 协议、域名、端口相同
    http://www.oldboy.cn/about.html 协议、域名、端口相同
    https://www.oldboy.cn:443/user/login.html 协议不同 ( https和http )
    http:/www.oldboy.cn:5000/user/login.html 端口 不同( 5000和80)
    http://bbs.oldboy.cn/user/login.html 域名不同 ( bbs和www )

    同源策略针对ajax的拦截,代码:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="js/vue.js"></script>
        <script src="js/axios.js"></script>
    </head>
    <body>
        <div id="app">
            <input type="text" v-model="music"><button @click="get_music">查询歌曲</button>
        </div>
        <script>
            var vm = new Vue({
                el:"#app",
                data:{
                    music:"", // 歌曲标题
                },
                methods:{
                    get_music(){
                        axios.get(`http://tingapi.ting.baidu.com/v1/restserver/ting`,{
                            params:{
                                method:"baidu.ting.search.catalogSug",
                                query:this.music,
                            }
                        }).then(response=>{
                            console.log("查询数据成功!");
                        }).catch(error=>{
                            console.log("查询数据失败!");
                        })
                    }
                }
            })
        </script>
    </body>
    </html>

    上面代码运行错误如下:

    Access to XMLHttpRequest at 'http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=%E6%88%91%E7%9A%84%E4%B8%AD%E5%9B%BD%E5%BF%83' from origin 'http://localhost:63342' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

    上面错误,关键词:Access-Control-Allow-Origin

    只要出现这个关键词,就是访问受限。出现同源策略的拦截问题。

    4.2.5 ajax跨域(跨源)方案之CORS

    ajax跨域(跨源)方案:服务端授权[CORS],jsonp,服务端代理

     

    CORS是一个W3C标准,全称是"跨域资源共享",它允许浏览器向跨源的后端服务器发出ajax请求,从而克服了AJAX只能同源使用的限制。

    实现CORS主要依靠后端服务器中响应数据中设置响应头信息返回的。

     

    django的视图[伪代码]

    def post(request):

    response = new Response()

    response .set_header("Access-Control-Allow-Origin","http://localhost:63342")

    return response;

     

    // 在响应行信息里面设置以下内容:
    Access-Control-Allow-Origin: ajax所在的域名地址
    
    Access-Control-Allow-Origin: www.oldboy.cn  # 表示只允许www.oldboy.cn域名的客户端的ajax跨域访问
    
    // * 表示任意源,表示允许任意源下的客户端的ajax都可以访问当前服务端信息
    Access-Control-Allow-Origin: *

    jsonp

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <button onclick="getdata()">获取数据</button>
    <script>
        function getdata(){
            // 发送jsonp
            // 1. 创建script标签,并制定src为api地址,并追加到head标签中
            let script = document.createElement("script")
            // callback 就是服务端配合我们返回调用的方法名,把服务端数据作为参数给callback的值对应方法进行调用
            script.src="http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=setdata";
            document.head.append(script)
            console.log(script)
        }
    
        function setdata(data){
            // 这里就是响应数据的处理方法。
            console.log(data);//把数据显示到html页面
        }
    </script>
    </body>
    </html>

    总结:

    0. 同源策略:浏览器的一种保护用户数据的一种安全机制。
       浏览器会限制ajax不能跨源访问其他源的数据地址。
       同源:判断两个通信的地址之间,是否协议,域名[IP],端口一致。
       
       ajax:  http://127.0.0.1/index.html
       api数据接口:  http://localhost/index
       
       这两个是同源么?不是同源的。是否同源的判断依据不会根据电脑来判断,而是通过协议、域名、端口的字符串是否来判断。
       
    1. ajax默认情况下会受到同源策略的影响,一旦受到影响会报错误如下:
         No 'Access-Control-Allow-Origin' header is present on the requested resource
    
    2. 解决ajax只能同源访问数据接口的方式:
       1. CORS,跨域资源共享,在服务端的响应行中设置:
          Access-Control-Allow-Origin: 允许访问的域名地址
       2. jsonp
             所谓的jsonp本质上来说不是ajax技术,jsonp的核心实现是依靠script本身加载外部js文件来实现的。
             当然,实现jsonp技术,也需要服务端的配合
       3. 是否服务端代理
          思路:通过python来请求对应的服务器接口,客户端和python这边处于同源,那么就实现了服务端代理

    作业

    1. 在作业.html的代码基础上,完成商品数量的加减,注意商品数量如果低于0个,则自动删除当前商品
    2. 在作业.html的代码基础上,完成购物车总价格的计算。
    3. 使用ajax获取北京天气,并把昨天和未来5天天气情况以表格格式展示到html页面中。

    作业1、2答案

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
        #goods table{
            width: 600px;
            border:1px solid #000;
            border-collapse: collapse;
        }
        #goods td,#goods th{
            border: 1px solid #000;
        }
        #goods .box{
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
            background-color: #eee;
            width: 280px;
            height: 160px;
            padding: 40px 80px;
        }
        </style>
        <script src="vue.js"></script>
    </head>
    <body>
        <div id="goods">
            <button @click="is_show=true;goods_index=-1;">添加商品</button>
            <table>
                <tr>
                    <th>商品编号</th>
                    <th>商品标题</th>
                    <th>商品数量</th>
                    <th>商品价格</th>
                    <th>操作</th>
                </tr>
                <tr v-for="goods,index in goods_list">
                    <td>{{index+1}}</td>
                    <td>{{goods.name}}</td>
                    <td>
                        <button @click="sub(index)">-</button>
                        <input type="text" @keyup="check(index)" size="2" v-model="goods.num">
                        <button @click="goods.num++">+</button>
                    </td>
                    <td>{{goods.price.toFixed(2)}}</td>
                    <td>
                        <button @click="update(index)">编辑</button>
                        <button @click="del(index)">删除</button>
                    </td>
                </tr>
                <tr>
                    <td colspan="5">总计: {{total}}元</td>
                </tr>
            </table>
            <div class="box" v-show="is_show">
                商品标题: <input type="text" v-model="goods_name"><br><br>
                商品数量: <input type="text" v-model="goods_num"><br><br>
                商品价格: <input type="text" v-model="goods_price"><br><br>
                <button @click="save">保存</button>
                <button @click="cancel">取消</button>
            </div>
        </div>
        <script>
            var vm = new Vue({
                el:"#goods",
                data:{
                    is_show:false,
                    goods_name:"",
                    goods_num:"",
                    goods_price:"",
                    goods_index:-1, // 当前本次操作的商品信息[-1表示新增,大于0表示编辑]
                    goods_list:[
                        {"name":"python入门","num":27,"price":150},
                        {"name":"python进阶","num":21,"price":100},
                        {"name":"python高级","num":17,"price":75},
                        {"name":"python研究","num":37,"price":60},
                        {"name":"python放弃","num":57,"price":110},
                    ]
                },
                computed:{
                    total(){
                        // 计算购物车中所有商品总价格
                        let sum = 0;
                        /*
                          for ... in 时,遍历出来的数据是当前数组的下标或者对象的属性名称
                          for ... of 时,遍历出来的数据是当前数组的成员或者对象的属性值
                         */
                        for(let goods of this.goods_list){
                            sum += parseInt(goods.num) * parseFloat(goods.price);
                        }
                        return sum.toFixed(2);
                    }
                },
                methods:{
                    check(index){
                        var goods = this.goods_list[index];
                        if(goods.num<1){
                            this.goods_list.splice(index,1);
                        }
                    },
                    sub(index){
                      // 商品数量的减少
                      var goods = this.goods_list[index];
                      goods.num--;
                      // 如果当前商品数量为0,则删除商品
                      if(goods.num<1){
                          this.goods_list.splice(index,1);
                      }
                    },
                    save(){
                        // 保存数据[添加数据]
                        if(this.goods_index==-1){
                            this.goods_list.push({
                                "name":this.goods_name,
                                "num":parseInt(this.goods_num),
                                "price":parseFloat(this.goods_price),
                            });
                        }else{
                            // 能在编辑商品的时候,修改数量为0的时候也删除商品吗
                            if(this.goods_num<1){
                                this.goods_list.splice(this.goods_index,1);
                            }else{
                                this.goods_list[this.goods_index].name=this.goods_name;
                                this.goods_list[this.goods_index].num=parseInt(this.goods_num);
                                this.goods_list[this.goods_index].price=parseFloat(this.goods_price);
                            }
                        }
    
                        this.cancel();
                    },
                    cancel(){
                        this.is_show=false;
                        this.goods_index= -1;
                        this.goods_name= "";
                        this.goods_num= "";
                        this.goods_price= "";
                    },
                    del(index){
                        // 删除数据
                        this.goods_list.splice(index,1);
                    },
                    update(index){
                        // 先弹窗
                        this.is_show=true;
                        // 显示当前编辑的商品信息
                        this.goods_index=index;
                        this.goods_name=this.goods_list[index].name;
                        this.goods_num=this.goods_list[index].num;
                        this.goods_price=this.goods_list[index].price;
                        // 当用户点击保存时,修改对应数据
                    }
                }
            })
        </script>
    </body>
    </html>
    作业1、2参考答案

    作业3答案

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="vue.js"></script>
        <script src="axios.js"></script>
    
    </head>
    <body>
    <div id="app">
        <input type="text" v-model="city">
        <button @click="get_weather">获取天气</button>
    </div>
    <script>
        let vm = new Vue({
            el: "#app",
            data: {
                city: '上海'
            },
            // 在初始化的时候自动发送ajax获取数据
            methods: {
                get_weather() {
                    axios.get('http://wthrcdn.etouch.cn/weather_mini?', {
                        params: {city: this.city},
                        headers: {},
                    }).then(response => {
                        console.log(response.data)
                    }).catch(error => {
                        console.log('请求失败')
                    })
                }
            }
        });
    </script>
    </body>
    </html>
    作业3答案
  • 相关阅读:
    HMM (隐马尔可夫) 推导 (上)
    图模型初识
    K-means 和 EM 比较
    EM-高斯混合模型
    EM算法-完整推导
    EM算法直观认识
    pandas 之 时间序列索引
    K-Means 算法
    接口。
    第一册:lesson ninety-nine。
  • 原文地址:https://www.cnblogs.com/wgwg/p/13174597.html
Copyright © 2020-2023  润新知