Ajax技术

什么是Ajax

Ajax 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。

有什么用?(在不刷新页面的情况下向服务器请求数据)

咱们的网页如果想要刷新局部内容。 那么需要重新载入整个网页。用户体验不是很好。 就是为了解决局部刷新的问题。 保持其他部分不动,只刷新某些地方。

怎么用

ajax的工作流程

  1. 创建XMLHttpRequest对象
 	let xhr = new XMLHttpRequest();
  1. 设置请求
	xhr.open('get','https://autumnfish.cn/api/joke');
	
  1. 发送请求
	xhr.send();
  1. 注册回调函数
  • 这个函数不是立即执行的,而是等服务器把数据响应返回才会执行 (PS:什么时候执行取决于你的网速快慢)
	xhr.onload = function(){
	console.log(xhr.responsetText);
	}

案例:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
        body {
            text-align: center;
        }

        input {
            border: 4px solid gray;
            padding: 10px;
            font-size: 25px;
            background-color: skyblue;
            color: white;
            border-radius: 10px;
            cursor: pointer;
            outline: none;
        }

        .joke-container {
            width: 500px;
            height: 500px;
            border: 1px solid gray;
            border-radius: 10px;
            padding-left: 10px;
            margin: 10px auto;
            font-size: 30px;
            text-align: left;
            text-indent: 60px;
        }
    </style>
</head>

<body>
    <input type="button" value="点我看笑话" class="getJoke" />
    <div class="joke-container"></div>

    <script src="./jquery-1.12.4.js"></script>
    <script>
        /*
          随机获取笑话的接口
      
          - 请求地址:https://autumnfish.cn/api/joke
          - 请求方法:get
          - 请求参数:无
          - 响应内容:随机笑话
      
          思路步骤
      
          1. 给按钮注册点击事件 onclick
          2. 通过ajax调用 笑话接口
          3. 数据返回之后 显示到div中
       */
      $('.getJoke').on('click',function(){
        // 1.创建小黄人对象
        let xhr = new XMLHttpRequest();
            // 2.设置请求的方法和地址
            xhr.open('get', 'https://autumnfish.cn/api/joke');
            // 3.发送请求
            xhr.send();
            // 4.注册回调函数
            xhr.onload = function () {
                // console.log(xhr.responseText)
                // 显示到div中
                $('.joke-container').text(xhr.responseText);
            };
      });
        
    </script>
</body>

</html>

在这里插入图片描述

Ajax接口文档的调用

  • 接口:Web服务器提供,让ajax请求的网络地址称之为接口,简称API
  • 接口文档:为了方便开发人员使用,我们的后台小伙伴会提供一种专门的文档,称之为接口文档
    • 接口文档,又称为API文档,可以理解为接口的使用说明书
    • 接口文档的本质 :其实就是后台开发(如php)他们写的函数注释。后台在处理请求的时候一般都会写一些函数
  • 一个标准的接口文档至少要包含以下三种信息(只能多,不能少)
    • a.请求的地址 (url)
    • b.请求的方法 (get或者post)
    • c.请求的参数

get请求提交参数

  • 接口文档:查询英雄外号
    • 请求地址:https://autumnfish.cn/api/hero/simple
    • 请求方法:get
    • 请求参数:name
  • get传参格式:url?key=value
  • 示例: https://autumnfish.cn/api/hero/simple?name=亚索
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
</head>

<body></body>

</html>
<script>
    /*
      接口文档:根据英雄 姓名 查询英雄的 外号
      请求地址:https://autumnfish.cn/api/hero/simple
      请求方法:get
      请求参数:name
      响应内容:英雄外号
  
      1.get传参格式: url?key=value
      2.示例: https://autumnfish.cn/api/hero/simple?name=亚索
    */

    // 1.实例化ajax对象
    let xhr = new XMLHttpRequest();
    // 2.设置请求方法和地址
    // get请求的数据直接添加在url的后面 格式是 url?key=value
    xhr.open('get', 'https://autumnfish.cn/api/hero/simple?name=亚索');
    // 3.发送请求
    xhr.send();
    // 4.注册回调函数
    xhr.onload = function () {
        alert(xhr.responseText)
    };
    
</script>

post请求

post请求与get请求区别

  1. 传参方式不同
  • get请求参数直接在url后面拼接 : url?key=value
  • post请求参数不能写在url,需要在send方法中传参
    • xhr.send('key=value')
  1. post请求需要设置请求头(post请求才需要设置,这是固定格式语法,强烈建议大家复制粘贴)
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');

案例:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
        .info {
            color: red;
        }
    </style>
</head>

<body>
    <h2>用户注册</h2>
    <input type="text" placeholder="请输入注册的用户名" class="username" />
    <span class="info"></span>
    <br />
    <input type="button" value="注册" class="submit" />
</body>

</html>
<script src="./libs/jquery-1.12.4.min.js"></script>
<script>

    /* 
    请求方法get和post区别: 传参方式不同
        get请求: 直接在url后面拼接参数
            * 参数在url中,安全性不高
        post请求:
            1.需要设置请求头(固定语法):xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
                * 注意:这是固定格式,错一个字母都不行,强烈建议复制粘贴
            2.使用xhr的send方法发送参数: xhr.send('参数名=参数值');
                * 注意:不要加前面的? 
    */

    /*
  用户注册
  - 请求地址:https://autumnfish.cn/api/user/register
  - 请求方法:post
  - 请求参数:username
  
  1. 注册点击事件  : submit
  2. 获取输入框文本:username
  3. 通过ajax调用接口:参数为输入框文本
  4. 数据返回之后显示到info中
  */

    $(function () {
        //1.注册点击事件
        $('.submit').on('click', function () {
            //2.获取输入框文本
            let username = $('.username').val();
            //3.ajax发送请求
            //(1).实例化ajax对象
            let xhr = new XMLHttpRequest();
            //(2).设置请求方法和地址
            xhr.open('post', 'https://autumnfish.cn/api/user/register');
            //(3).设置请求头(post请求才需要设置)
            xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
            //(4).发送请求 : 参数格式  'key=value'
            xhr.send('username=' + username);
            //(5).注册回调函数
            xhr.onload = function () {
                $('.info').text(xhr.responseText);
            };
        });
    });

</script>

JSON数据格式解析

为了方便数据的保存以及传递,就有了一些通用的数据格式(前端js和后端php、java等都支持的数据格式),常用的曾经有JSON和XML,但是现在基本上都是用JSON,XML已经退出了历史的舞台,基本看不到了

  • JSON是一种数据格式,本质是字符串
  • 作用: 解决跨平台的问题,一般服务器返回的数据都是json格式
  • JSON格式特点
    • 属性名和属性值都是字符串(需要使用双引号包括)
    • 如果属性是布尔值和数字类型,则可以省略字符串
  • JSON格式与JS对象互转
    • JOSN---->JS :JSON.parse(json数据)
    • JS------>JSON :JSON.stringify(js对象)

案例:(lol英雄查询)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
        body {
            background-color: black;
            text-align: center;
        }

        .hero {
            padding: 10px;
            font-size: 25px;
            border-radius: 10px;
            outline: none;
        }

        .bg {
            width: 1000px;
            height: 590px;
            margin: 10px auto;
            background-image: url(http://img1.dwstatic.com/lol/1512/315320556654/1451366974753.jpg);
            background-repeat: no-repeat;
            background-size: 1000px 590px;
        }

        .bg .left {
            height: 590px;
            width: 300px;
            background-color: rgba(0, 0, 0, 0.5);
            padding-left: 20px;
            padding-top: 30px;
            box-sizing: border-box;
            overflow-y: auto;
        }

        .left span {
            color: white;
        }

        .left .name {
            margin-top: 30px;
            font-size: 30px;
        }

        .left .icon {
            width: 120px;
            height: 120px;
        }

        .left .title {
            margin-top: 20px;
            font-size: 50px;
            display: block;
            font-weight: 900;
        }

        .left .story {
            font-weight: 700;
            color: skyblue;
            text-align: left;
        }
    </style>
</head>

<body>
    <input type="text" class="hero" placeholder="输入英雄按下回车查询" />
    <div class="bg">
        <div class="left">
            <div>
                <span class="name">提莫 </span>
                <img class="icon" src="http://img.dwstatic.com/lol/1310/246295394773/1382341114833.png" alt="" />
            </div>
            <span class="title">迅捷斥候</span>
            <p class="story">团战可以输,大龙可以丢,高地可以破,提莫必须死</p>
        </div>
    </div>

    <script src="jquery-1.12.4.js"></script>

    <script>
        /* 
        请求地址:https://autumnfish.cn/api/hero/info
        示例:https://autumnfish.cn/api/hero/info?name=提莫
        请求方法:get
        请求参数:name
        */

        /*思路分析 
        1.给输入框注册键盘按下(onkeydown),监听enter键(e.keyCode == 13)
        2.获取输入框文本
        3.ajax发送请求
        4.服务器响应之后渲染数据
        */


        //1.给输入框注册键盘按下
        $('.hero').keydown(function (e) {
            if (e.keyCode == 13) {
                // 获得英雄姓名
                let heroName = $(this).val();
                // 实例化xhr对象
                let xhr = new XMLHttpRequest();
                xhr.open('get', 'https://autumnfish.cn/api/hero/info?name=' + heroName);
                xhr.send();
                xhr.onload = function () {
                    console.log(xhr.responseText);
                    // 4.1先将服务器返回的json格式字符串转成js对象
                    let backdata = JSON.parse(xhr.responseText)
                    console.log(backdata);
                    // 4.2渲染页面
                    $('.name').text(backdata.name);
                    $('.bg').css('background', 'url(' + backdata.bg + ')')
                    $('.icon').css('src', backdata.icon);
                    $('.story').text(backdata.story);
                    $('.title').text(backdata.title);
                };
            }

        });
    </script>
</body>

</html>

在这里插入图片描述

ajax多参数传递

  • 1.多参数传递格式 : key1=valu1&key2=value2
    • a. 多个参数之间用 $符号隔开
    • b.参数之间不能有空格
  • 2.post多参数传递格式与get是一致的,只是参数要放到send()方法中而已
    案例:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script src="jquery-1.12.4.js"></script>
    <script>
        /*学习目标: ajax传递多参数
            get与post传递多参数语法一致:  
                get :  url?key1=value1&key2=value2
                post: xhr.send('key1=value1&key2=value2')
        
        */
        // 1.实例化ajax对象   
        let xhr = new XMLHttpRequest();
        // 2.设置方法和地址
        xhr.open('post', 'http://www.tuling123.com/openapi/api');

        // 3.设置头
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

        // 4.发送请求
        xhr.send('key=2162602fd87240a8b7bba7431ffd379b&info=你好啊');

        xhr.onload = function () {
            console.log(xhr.responseText);
        }
    </script>
</body>

</html>

jQuery使用ajax

  • 文档
  • $.get() : 发送get请求
  • $.post() : 发送post请求
  • $.ajax() : 发送get与post(最常用)
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
</head>

<body>
    <input type="button" value="get方法" class="get" />
    <input type="button" value="post方法" class="post" />
    <input type="button" value="ajax方法" class="ajax" />

    <script src="jquery-1.12.4.js"></script>

    <script>
        /* 学习目标: jq使用ajax
          $.get()     :  发送get请求
          $.post()    :  发送post请求
          $.ajax()    :  发送get+post请求
        
        */

        // 1.$.get():发送get请求
        $('.get').click(function () {
            /**
             * @description:发送get请求
             * @param {type} url:地址
             * @param {type} data:参数
             * @param {function} callback:响应回调
             * @return: 
             */
            //    $.get('https://autumnfish.cn/api/hero/detail','name=娑娜',function(backdata){
            //     console.log(backdata);
            //    });
            $.get('https://autumnfish.cn/api/hero/detail', {
                name: '娑娜'
            }, function (backdata) {
                console.log(backdata);

            });
        });

        // 2.$.post():发送post请求
        $('.post').click(function () {
            /**
             * @description:发送post请求
             * @param {type} url:地址
             * @param {type} data:参数
             * @param {function} callback:响应回调
             * @return: 
             */
            $.post('http://www.tuling123.com/openapi/api', {
                key: '2162602fd87240a8b7bba7431ffd379b',
                info: 'hello'


            }, function (backdata) {
                console.log(backdata);

            });
        });

        // $.ajax():发送get与post 
        $('.ajax').click(function () {
            /**
             * @description:
             * @param {对象}
             * url:请求路径
             * type:请求方法 
             * data:请求参数
             * success:响应回调function(backData){}
             * @return: 
             */
            // $.ajax({
            //     url:'https://autumnfish.cn/api/hero/detail',
            //     type:'get',
            //     data:{
            //         name:'娑娜'
            //     },
            //     success:function(backdata){
            //         console.log(backdata);
            //     }
            // });

            $.ajax({
                url:'http://www.tuling123.com/openapi/api',
                type:'post',
                data:{
                    key:'2162602fd87240a8b7bba7431ffd379b',
                    info:'hello'
                },
                success:function(backdata){

                    console.log(backdata);
                }
            });
        });
    </script>
</body>

</html>
  • 注意点
    • 设置dataType属性检测json格式
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

    <script src="./libs/jquery-1.12.4.js"></script>
    <script>
        /* 
        jq使用ajax的注意点 : 设置dataType属性检测json格式
        */

       $.ajax({
           url:'http://www.tuling123.com/openapi/api',
           type:'post',
           /* 
            限制服务器返回的数据为json格式
            如果是json:jq会自动帮我帮我们转成json
            如果不是json:jq不会执行success方法,避免代码出错

           */
          dataType:'json',
          data:{
              key:'2162602fd87240a8b7bba7431ffd379b',
              info:'hello'
          },
          success:function(backdata){
              console.log(backdata);
          }
       });
        
    </script>
</body>

</html>
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值