AJAX基础

$get()发起不带参数的请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="lib/jquery.js"></script>

</head>
<body>
<button id="btnGET">发起不带参数的GET请求</button>

<script>
   $(function (){
       $('#btnGET').on('click',function (){
          $.get('http://www.liulongbin.top:3006/api/getbooks',function (res){
              console.log(res)
          })
       })
   })
</script>

</body>
</html>

$get()发起带参数的请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="lib/jquery.js">

    </script>
</head>
<body>
<button id="btnGETINFO">发起带参数的GET请求</button>
<script>
    $(function (){
        $('#btnGETINFO').on('click',function (){
            $.get('http://www.liulongbin.top:3006/api/getbooks',{id:1},function (res){
                console.log(res)
            })
        })
    })
</script>
</body>
</html>

使用POST提交数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="lib/jquery.js"></script>
</head>
<body>
<button id="btnPOST">发起POST请求</button>
<script>
    $(function (){
        $('#btnPOST').on('click',function (){
            $.get('http://www.liulongbin.top:3006/api/addbook',{bookname:'水浒传',author:'施耐庵',publisher:'天津图书出版社'},function (res){
                console.log(res)
            })
        })
    })
</script>
</body>
</html>

$ajax()函数发起GET请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="lib/jquery.js"></script>
</head>
<body>
<button id="btnGET">发起GET请求</button>

<script>
    $(function (){
        $('#btnGET').on('click',function (){
            $.ajax({
               type:'GET',
                url:'http://www.liulongbin.top:3006/api/getbooks',
                data:{
                   id:1
                },
                success:function (res){
                    console.log(res)
                }
            })
        })
    })
</script>

</body>
</html>

$ajax()发起POST请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="lib/jquery.js"></script>
</head>
<body>
<button id="btnPOST">发起POST请求</button>

<script>
    $(function (){
        $('#btnPOST').on('click',function (){
            $.ajax({
                type:'POST',
                url:'http://www.liulongbin.top:3006/api/getbooks',
                data:{
                    bookname:'史记',
                    author:'司马迁',
                    publisher: '上海图书出版社'
                },
                success:function (res){
                    console.log(res)
                }
            })
        })
    })
</script>

</body>
</html>

使用传统方法渲染UI结构

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./lib/jquery.js"></script>
</head>
<body>
<div id="title"></div>
<div>姓名:<span id="name"></span></div>
<div>年龄:<span id="age"></span></div>
<div>会员:<span id="isVIP"></span></div>
<div>注册时间:<span id="regTime"></span></div>
<div>
    爱好:
    <ul id="hobby">
        <li>爱好1</li>
        <li>爱好2</li>
    </ul>
</div>
<script>

    var data={
        title:'<h3>用户信息</h3>',
        name:'zs',
        age:20,
        isVIP:true,
        regTime:new Date(),
        hobby:['吃饭','睡觉','打豆豆']
    }
    $(function (){
        $('#name').html(data.name)
        $('#title').html(data.title)
        $('#age').html(data.age)
        $('#isVIP').html(data.isVIP)
        $('#regTime').html(data.regTime)
        var rows=[]
        $.each(data.hobby,function (i,item){
            rows.push('<li>'+item+'</li>')
        })
        $('#hobby').html(rows.join(''))

    })
</script>
</body>
</html>

演示模板引擎的使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
<!--    1.导入模板引擎-->
<!--    在window全局,多一个函数,叫做template(’模板的id',需要渲染的数据对象-->
    <script src="lib/template-web.js"></script>
    <script src="./lib/jquery.js"></script>

</head>
<body>
<!--//3.定义模板-->
<!--        // 模板的HTML结构必须定义到script标签中-->
<div id="container"></div>

<script type="text/html" id="tpl-user">
    <h1>{{name}}   ----   {{age}}</h1>
    {{@ test}}
    <div>
        {{if flag===0}}
        flag的值是0
        {{else if flag===1}}
        flag的值是1
        {{/if}}
    </div>
    <ul>
        {{each hobby}}
        <li>
            索引是:{{$index}},循环项是:{{$value}}
        </li>
        {{/each}}
    </ul>
    <h3>{{regTime|dateFormat}}</h3>
</script>

<script>
    template.defaults.imports.dateFormat=function (date){
        //console.log(date)
        var y=date.getFullYear()
        var m=date.getMonth()
        var d=date.getDate()

        return y+'-'+m+'-'+d
    }
    //2.定义需要渲染的数据
    var data={name:'zs',age:20,test:'<h3>测试原文输出</h3>',flag:1,hobby:['吃饭','睡觉','写代码'],regTime:new Date()}
    //4.调用template函数
    var htmlStr=template('tpl-user',data)
    console.log(htmlStr)
    //5.渲染HTML结构
    $('#container').html(htmlStr)
</script>
</body>
</html>

exec函数的基本使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var str='hello'
    var pattern=/o/

    var result=pattern.exec(str)
    console.log(result)
</script>
</body>
</html>

提取分组

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var str='<div>我是{{name}}</div>'
    var pattern=/{{([a-zA-Z]+)}}/

    var result=pattern.exec(str)
    console.log(result)
</script>
</body>
</html>

字符串的replace操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var str='<div>我是{{name}}</div>'
    var pattern=/{{([a-zA-Z]+)}}/

    var patternResult=pattern.exec(str)
    str=str.replace(patternResult[0],patternResult[1])
    console.log(str)
</script>
</body>
</html>

字符串的多次replace操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var str='<div>{{name}}今年{{age}}</div>'
    var pattern=/{{\s*([a-zA-Z]+)\s*}}/

    //第一次匹配
    var res1=pattern.exec(str)
    str=str.replace(res1[0],res1[1])
    console.log(str)

    //第二次匹配
    var res2=pattern.exec(str)
    str=str.replace(res2[0],res2[1])
    console.log(str)
</script>
</body>
</html>

使用while循环进行replace操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var str='<div>{{name}}今年{{age}}</div>'
    var pattern=/{{\s*([a-zA-Z]+)\s*}}/

    var patternResult=null
    while (patternResult=pattern.exec(str)){
        str=str.replace(patternResult[0],patternResult[1])
    }
    console.log(str)
</script>
</body>
</html>

replace替换为真值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var data={name:'张三',age:20}

    var str='<div>{{name}}今年{{age}}岁了</div>'
    var pattern=/{{\s*([a-zA-Z]+)\s*}}/

    var patternResult=null
    while (patternResult=pattern.exec(str)){
        str=str.replace(patternResult[0],data[patternResult[1]])
    }
    console.log(str)
</script>
</body>
</html>

调用自己的模板引擎

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/template.js"></script>
</head>
<body>
<div id="user-box"></div>
<script type="text/html"id="tpl-user">
<div>姓名:{{name}}</div>
<div>年龄:{{age}}</div>
<div>性别:{{gender}}</div>
<div>住址:{{address}}</div>

</script>

<script>
    //定义数据
    var data={name:'zs',age:28,gender:'男',address:'北京顺义'}

    //调用模板引擎
    var htmlStr=template('tpl-user',data)

    //渲染HTML结构
    document.getElementById('user-box').innerHTML=htmlStr
</script>
</body>
</html>

AJAX加强

使用xhr发送GET数据请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    //1.创建XHR对象
    var xhr=new XMLHttpRequest()
    //2.调用open函数
    xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks')
    //3.调用send函数
    xhr.send()
    //4.监听onreadystatechange事件
    xhr.onreadystatechange=function (){
        if(xhr.readyState===4&&xhr.status===200){
            //获取服务器响应的数据
            console.log(xhr.responseText)
        }
    }
</script>
</body>
</html>

发起带参数的GET请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  var xhr=new XMLHttpRequest()
  xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks?id=1')
  xhr.send()
  xhr.onreadystatechange=function (){
      if (xhr.readyState===4&&xhr.status===200){
          console.log(xhr.responseText)
      }
  }

</script>
</body>
</html>

GET携带参数的本质

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./lib/jquery.js">

    </script>
</head>
<body>
<script>
    // $.get('http://www.liulongbin.top:3006/api/getbooks',{id:1,bookname:'西游记'},function (res){
    //     console.log(res)
    // })

    $.ajax({
        method:'GET',
        url:'http://www.liulongbin.top:3006/api/getbooks',
        data:{
            id:1,
            bookname:'西游记'
        },
    success:function (res){
        console.log(res)
    }
    })
</script>
</body>
</html>

演示URL编码与解码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  var str='黑马程序员'
  var str2=encodeURI(str)
  console.log(str2)

   console.log('-----')
  var str3=decodeURI('%E9%BB%91%E9%A9%AC%E7%A8%8B%E5%BA%8F%E5%91%98')
  console.log(str3)
</script>
</body>
</html>

使用xhr发起POST请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    //1.创建一个xhr对象
    var xhr=new XMLHttpRequest()
    //2.调用open函数
    xhr.open('POST','http://www.liulongbin.top:3006/api/addbook')
    //3.设置Content-Type属性
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
    //4.调用send函数
    xhr.send('bookname=水浒传&author=施耐庵&publisher=上海图书出版社')
    //5.监听事件
    xhr.onreadystatechange=function (){
        if(xhr.readyState===4&&xhr.status===200){
            console.log(xhr.responseText)
        }
    }
</script>
</body>
</html>

JSON和JS对象之间的转换

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
  // var jsonStr='{"a":"Hello","o":"world"}'
  // var obj=JSON.parse(jsonStr)
  // console.log(obj)
  var obj2={a:'hello',b:'world',c:false}
  var str=JSON.stringify(obj2)
  console.log(str)
  console.log(typeof str)
</script>
</body>
</html>

演示JSON.parse函数的应用场景

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var xhr=new XMLHttpRequest()
    xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks')
    xhr.send()
    xhr.onreadystatechange=function (){
        if(xhr.readyState===4&&xhr.status===200){
            console.log(xhr.responseText)

            var result=JSON.parse(xhr.responseText)
            console.log(result)
        }
    }
</script>
</body>
</html>

测试

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/itheima.js"></script>
</head>
<body>
<script>
    // itheima({
    //     method:'GET',
    //     url:'http://www.liulngbin.top:3006/api/getbooks',
    //     data:{
    //         id:1
    //     },
    //     success:function (res){
    //         console.log(res)
    //     }
    //
    // })
    itheima({
        method:'POST',
        url:'http://www.liulngbin.top:3006/api/addbook',
        data:{
            bookname:'水浒传',
            author:'施耐庵',
            publisher:'北京图书出版社'

        },
        success:function (res){
            console.log(res)
        }

    })
</script>
</body>
</html>

设置超时时限

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var xhr=new XMLHttpRequest()

    //设置超时时间
    xhr.timeout=3000
    //设置超时以后的处理函数
    xhr.ontimeout=function (){
        console.log('请求超时了')
    }

    xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks')
    xhr.send()
    xhr.onreadystatechange=function (){
        if(xhr.readyState===4&&xhr.status===200){
            console.log(xhr.responseText)
        }
    }

</script>
</body>
</html>

演示FormData对象的基本使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    //1.创建formdata实例
    var fd=new FormData()
    //2.调用append函数,向fd中追加对象
    fd.append('uname','zs')
    fd.append('upwd','123456')

    var xhr=new XMLHttpRequest()
    xhr.open('POST','http://www.liulongbin.top:3006/api/formdata')
    xhr.send(fd)


    xhr.onreadystatechange=function (){
        if(xhr.readyState===4&&xhr.status===200){
            console.log(JSON.parse(xhr.responseText))
        }
    }
</script>
</body>
</html>

使用FormData快速获取表单中的数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form id="form1">
    <input type="text" name="uname" autocomplete="off"/>
    <input type="password" name="upwd"/>
    <button type="submit">提交</button>
</form>
<script>
    //1.通过DOM操作,获取到form表单
    var form=document.querySelector('#form1')

    form.addEventListener('submit',function (e){
        //阻止表单的默认提交行为
        e.preventDefault()

        //创建FormData,快速获取到form表单中的数据
        var fd=new FormData(form)
        var xhr=new XMLHttpRequest()
        xhr.open('POST','http://www.liulongbin.top:3006/api/formdata')
        xhr.send(fd)


        xhr.onreadystatechange=function (){
            if(xhr.readyState===4&&xhr.status===200){
                console.log(JSON.parse(xhr.responseText))
            }
        }
    })
</script>
</body>
</html>

上传文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--1.文件选择框-->
<input type="file" id="file1"/>
<!--2.上传文件的按钮-->
<button id="btnUpload">上传文件</button>
<br/>
<!--3.img标签,来显示上传成功以后的图片-->
<img src="" alt="" id="img" width="800"/>
<script>
    //1.获取文件上传按钮
    var btnUpload=document.querySelector('#btnUpload')
    //2.为按钮绑定单击事件处理函数
    btnUpload.addEventListener('click',function (){
        //3.获取到用户选择的文件列表
        var files=document.querySelector('#file1').files
        if (files.length<=0){
            return alert('请选择要上传的文件!')
        }
        var fd=new FormData()
        //将用户选择的文件添加到FormData中去
        fd.append('avatar',files[0])

        var xhr=new XMLHttpRequest()
        xhr.open('POST','http://www.liulongbin.top:3006/api/formdata')
        xhr.send(fd)


        xhr.onreadystatechange=function (){
            if(xhr.readyState===4&&xhr.status===200){
                var data=(JSON.parse(xhr.responseText))
               if(data.status===200){
                   //上传成功
                    document.querySelector('#img').src='http://www.liulongbin.top:3006'+data.url
               }else{
                   //上传失败
                   console.log('图片上传失败'+data.message)
               }
            }
        }
    })
</script>
</body>
</html>

计算文件上传进度

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="./lib/bootstrap.css"/>
    <script src="./lib/jquery.js"></script>
</head>
<body>
<!--1.文件选择框-->
<input type="file" id="file1"/>
<!--2.上传文件的按钮-->
<button id="btnUpload">上传文件</button>

<!--bootstrap中的进度条-->
<div class="progress" style="width: 500px;margin: 15px 10px;">
    <div class="progress-bar progress-bar-striped active"  style="width: 0%" id="percent">
        0%
    </div>
</div>

<br/>
<!--3.img标签,来显示上传成功以后的图片-->
<img src="" alt="" id="img" width="800"/>
<script>
    //1.获取文件上传按钮
    var btnUpload=document.querySelector('#btnUpload')
    //2.为按钮绑定单击事件处理函数
    btnUpload.addEventListener('click',function (){
        //3.获取到用户选择的文件列表
        var files=document.querySelector('#file1').files
        if (files.length<=0){
            return alert('请选择要上传的文件!')
        }
        var fd=new FormData()
        //将用户选择的文件添加到FormData中去
        fd.append('avatar',files[0])

        var xhr=new XMLHttpRequest()
        //监听文件上传速度
        xhr.upload.onprogress=function (e){
            if(e.lengthComputable){

                //计算出上传速度
                var procentComplete=Math.ceil((e.loaded/e.total)*100)
                console.log(procentComplete)
                //设置进度条
                $('#percent').attr('style','width:'+procentComplete+'%;').html(procentComplete)
            }
        }
        xhr.upload.onload=function (){
            $('#percent').removeClass().addClass('progress-bar progress-bar-success')
        }
        xhr.open('POST','http://www.liulongbin.top:3006/api/formdata')
        xhr.send(fd)


        xhr.onreadystatechange=function (){
            if(xhr.readyState===4&&xhr.status===200){
                var data=(JSON.parse(xhr.responseText))
                if(data.status===200){
                    //上传成功
                    document.querySelector('#img').src='http://www.liulongbin.top:3006'+data.url
                }else{
                    //上传失败
                    console.log('图片上传失败'+data.message)
                }
            }
        }
    })
</script>
</body>
</html>

使用Jquery实现文件上传

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./lib/jquery.js">

    </script>
</head>
<body>
<input type="file" id="file1"/>
<button id="btnUpload">上传文件</button>
<br/>
<img src="./images/loading.gif"alt=""style="display: none;" id="loading"/>
<script>
    $(function (){
        //监听到Ajax请求被发起了
        $(document).ajaxStart(function (){
            $('#loading').show()
        })
        //监听到Ajax完成的事件
        $(document).ajaxStop(function (){
            $('#loading').hide()
        })
        $('#btnUpload').on('click',function (){
            var files=$('#file1')[0].files
            if(files.length<=0){
                return alert('请选择文件后在上传')
            }
           var fd=new FormData()
            fd.append('avatar',files[0])
            //发起jquery的Ajax请求,上传文件
            $.ajax({
                method:'POST',
                url:'http://www.liulongbin.top:3006/api/upload.avatar',
                data:fd,
                processData:false,
                contentType:false,
                success:function (res){
                    console.log(res )
                }
            })
        })
    })
</script>
</body>
</html>

AXIOS的基本使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./lib/axios.js"></script>
</head>
<body>
<button id="btn1">发起GET请求</button>
<button id="btn2">发起POST请求</button>
<button id="btn3">直接发起GET请求</button>
<button id="btn4">直接发起POST请求</button>

<script>
    document.querySelector('#btn1').addEventListener('click',function (){
        var url='http://www.liulongbin.top:3006/api/get'
        var paramsObj={name:'zs',age:20}
        axios.get(url,{params:paramsObj}).then(function (res){
            console.log(res.data)
        })
    })

    document.querySelector('#btn2').addEventListener('click',function (){
        var url='http://www.liulongbin.top:3006/api/post'
        var dataObj={address:'北京',location:'顺义'}
        axios.post(url,{params:dataObj}).then(function (res){
            var result=res.data
            console.log(result)
        })
    })

    document.querySelector('#btn3').addEventListener('click',function (){
        var url='http://www.liulongbin.top:3006/api/get'
        var paramsData={name:'钢铁侠',age:35}
        axios({
            method:'GET',
            url:url,
            params:paramsData
        }).then(function (res){
            console.log(res.data)
        })
    })

    document.querySelector('#btn4').addEventListener('click',function (){
        axios({
            method:'POST',
            url:'http://www.liulongbin.top:3006/api/post',
            data:{
                name:'哇哈哈',
                age:20,
                gender:'女'
            }

        }).then(function (res){
            console.log(res.data)
        })
    })
</script>
</body>
</html>

Q.E.D.