Ajax学习

具体模板可参考:域名正在测试,该地址临时使用密码(He371226)内部的AJAX文件

所有的使用原生发起请求的均已创建XMLHttpRequest对象为xhr

var xhr = new XMLHttpRequest()

导入axios,jQuery,bootstrap需自行导入

XMLHttpRequest

原生JS发起GET请求

            xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
            xhr.send()
            xhr.onreadystatechange = function () {

                console.log(xhr.responseText);
            }

原生JS发起POST请求

            xhr.open('POST', 'http://www.liulongbin.top:3006/api/addbook')
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
            xhr.send('bookname=你好&author=haha&publisher=中国')
            xhr.onreadystatechange = function () {
                if (xhr.readyState = 4 && xhr.status == 200) {
                    console.log(xhr.responseText);
                }
            }

 jQuery

用jQuery发起get请求(无参数)

    $.get('http://www.liulongbin.top:3006/api/getbooks', function (res) {
        console.log(res.data);
    })

用jQuery发起get请求(有参数)

    $.get('http://www.liulongbin.top:3006/api/getbooks', { id: 1 }, function (req) {
                console.log(req.data);
        })

用jQuery发起post请求

$.post('http://www.liulongbin.top:3006/api/addbook', { bookname: '中国历史', author: '中国人民', publisher: '中国出版社' },
        function (res) {
        console.log(res);
        }
    )

用jQuery发起ajax(post)请求

        $('#ajaxPost').on('click', function () {
            $.ajax({
                type: 'POST',
                url: 'http://www.liulongbin.top:3006/api/addbook',
                data: {
                    bookname: '数据结构',
                    author: '啦啦啦',
                    publisher: '中国出版社'
                },
                success: function (res) {
                    console.log(res);
                }
            })

用jQuery发起ajax(get)请求

            $.ajax({
                type: 'GET',
                url: 'http://www.liulongbin.top:3006/api/getbooks',
                data: {
                    id: 1
                },
                success: function (res) {
                    console.log(res);
                }
            })

自行封装一个AJAX 

自行封装一个AJAX

//创建myajax
function resolveData(data){
    var arr = []
    for (var key in data){
        var str =key+'='+data[key]
        arr.push(str)
    }
    return arr.join('&')
}
function myajax(options){
    var xhr=new XMLHttpRequest()
    //把外界传来的参数对象转化为查询字符串
    var qs=resolveData(options.data)
    if(options.method.toUpperCase()==='GET'){
        xhr.open(options.method,options.url+'?'+qs)
        xhr.send()

    }else if(options.method.toUpperCase()==='POST'){
        xhr.open(options.method,options.url)
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        xhr.send(qs)
    }
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4&&xhr.status==200){
            var result=JSON.parse(xhr.responseText)
            options.success(result)
        }
    }
//调用myajax
//GET
myajax({
                method: 'GET',
                url: 'http://www.liulongbin.top:3006/api/getbooks',
                data: {

                },
                success: function (res) {
                    console.log(res);
                }
            })
//POST
myajax({
                method: 'POST',
                url: 'http://www.liulongbin.top:3006/api/addbook',
                data: {
                    bookname: '哈哈哈',
                    author: '啦啦啦',
                    publisher: 'eqeq'
                },
                success: function (res) {
                    console.log(res);
                }
            })
        })

超时访问

 xhr.timeout = 30
            xhr.ontimeout = function () {
                alert('访问超时!')
            }
            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);
                }
            }

formdata提交

直接由formdata提交

            //创建formdata
            var fd = new FormData()
            //通过append向fd中追加数据
            fd.append('name', 'haha')
            fd.append('upwd', '123456')
            xhr.open('POST', 'http://www.liulongbin.top:3006/api/formdata')
            //xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
            xhr.send(fd)
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    console.log(JSON.parse(xhr.responseText));
                }
            }

axios 

使用axios发起get请求

 var parmasObj = { name: 'zs', age: 20 }
axios.get('http://www.liulongbin.top:3006/api/get', { params: parmasObj }).then(function (res) {
    console.log(res.data);
    }, function (err) { })

使用axios发起post请求

var dataObj = { location: '北京', address: '顺义' }
axios.post('http://www.liulongbin.top:3006/api/post', dataObj).then(function (res) {
                console.log(res.data);
            }, function (err) { })

使用axios直接get请求

//get请求将数据写在params里

axios({
    method: 'GET',
    url: 'http://www.liulongbin.top:3006/api/get',
    data: {

    },
    params: {
    name: '钢铁侠',
    age: 35
    },
}).then(function (res) {
        console.log(res.data);
    }, function (err) { })

使用axios直接post请求

//post请求将数据写在data里

axios({
    method: 'POST',
    url: 'http://www.liulongbin.top:3006/api/post',
    data: {
        location: '西安',
        address: 'Xi`an University'
    },
    params: {

    }
}).then(function (res) {
    console.log(res.data);
}, function (err) { })

跨域

从一个根服务器访问另一个根服务器,受到浏览器保护会产生跨域,禁止访问,但是script标签的src属性可以来使用回调函数获得相应的值

原生jsonp 原理:利用script标签的src来使用回调函数获得相应的值

//?后面先为回调函数名称,然后是值
function abc(data) {
    console.log(data);
}
<script src="http://www.liulongbin.top:3006/api/jsonp?callback=abc&name=zs&age=18"></script>

Jquery jsonp 原理:jquery向header创建了一个script标签

$.ajax({
            url: "http://www.liulongbin.top:3006/api/jsonp?name=haha&age=18",
            //通过ajax发起jsonp请求必须指定 dataType: 'jsonp'
            dataType: 'jsonp',
            //自定义修改参数名,默认callback格式
            //jsonp:'123',
            //自定义修改回调函数名,默认jQueryxxxxxx格式
            //jsonpCallback: 'haha',
            success: function (res) {
                    console.log(res);  
            }
        })

表单

通过表单获取通过formData提交

HTML

<div style="border: solid 1px; width: 300px; margin: 10px; position: absolute;">
        <form id="form1">
            <b>通过表单获取通过formData提交</b>
            <input type="text" name="name" placeholder="账号">
            <input type="password" name="upwd" placeholder="密码">
            <br><input type="submit" value="提交">
        </form>
    </div>

JS

var form = document.querySelector('#form1')
        form.addEventListener('submit', function (e) {
            e.preventDefault()
            var fd = new FormData(form)
            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));
                }
            }
        })

原生JS 文件上传(bootstrap)

HTML

<div style="border: solid 1px; width: 300px; height: 100px; margin: 10px; position: relative; top: 0; left: 310px;">
        <b>原生JS 文件上传服务器及显示和进度条</b>
        <input type="file" id="file1">
        <!-- 进度条 -->
        <div class="progress" style="display: none;">
            <div class="progress-bar progress-bar-striped active" style="width: 0%;" id="percent"></div>
        </div>
        <button id="btnUpload">上传文件</button>
        <img src="" alt="" id="img" width="100px">
    </div>

JS

$('#btnUpload').on('click', function () {
            var files = document.querySelector('#file1').files
            if (files.length <= 0) {
                return alert('请选择上传的文件!')
            } else {
                var fd = new FormData()
                //将用户选的文件追加到fd中
                fd.append('avatar', files[0])
                xhr.open('POST', 'http://www.liulongbin.top:3006/api/upload/avatar')
                //计算上传进度
                xhr.upload.onprogress = function (e) {
                    if (e.lengthComputable) {
                        var percentComplete = Math.ceil((e.loaded / e.total) * 100)
                        $('.progress').attr('style', 'display:block')
                        $('#percent').attr('style', 'width:' + percentComplete + '%;display:block')
                        $('#percent').html(percentComplete + '%')
                    }
                }
                xhr.upload.onload = function () {
                    $('#percent').removeClass().addClass('progress-bar progress-bar-success')
                }
                xhr.send(fd)
                //监听上传成功
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        var data = JSON.parse(xhr.responseText)
                        console.log(data);
                        //打印图片
                        if (data.status === 200) {
                            document.getElementById('img').src = 'http://www.liulongbin.top:3006' + data.url
                        } else {
                            console.log(data.message);
                        }
                    }
                }
            }
        })

JQuery上传文件

HTML

<div
        style="border: solid 1px; width: 300px; height: 100px; margin: 10px; position: relative; top: -110px; left: 620px;">
        <b>Jqurey 文件上传服务器及显示和进度条</b>
        <input type="file" id="file2">
        <button id="btnUpload1">上传文件</button>
        <b id="b" style="display: none;">上传中</b>
        <img src="" alt="" id="img1" width="100px">
    </div>

JS

$('#btnUpload1').on('click', function () {
            //监听发起ajax请求
            $(document).ajaxStart(function () {
                $('#b').show()
            })
            //监听关闭ajax请求
            $(document).ajaxStop(function () {
                $('#b').hide()
            })
            var files = $('#file2')[0].files
            if (files.length <= 0) {
                return alert('请选择上传的文件!')
            } else {
                var fd = new FormData()
                fd.append('avatar', files[0])
                $.ajax({
                    method: 'POST',
                    url: 'http://www.liulongbin.top:3006/api/upload/avatar',
                    data: fd,
                    //不修改content-Type属性,使用formdata默认的content-Type值
                    contentType: false,
                    //不编码,直接将formdata上传
                    processData: false,
                    success: function (res) {
                        document.getElementById('img1').src = 'http://www.liulongbin.top:3006' + res.url
                    }
                })
            }
        })

JSON对象序列化与反序列化及编码

序列化:对象->字符串

反序列化:字符串->对象

JSON

 var jsonStr = '{"name":"jack","age":18,"id":123}'
            var obj = JSON.parse(jsonStr)
            var json1 = JSON.stringify({ name: 'marry', age: 16, id: 321 })
            console.log(typeof obj);
            console.log(obj);
            console.log(typeof json1 + ':' + json1);

get请求序列化&反序列化

$('#jsonPost').on('click', function () {
            xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
            xhr.send()
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    $.get('http://www.liulongbin.top:3006/api/getbooks', function (res) {
                        console.log(res);
                        var json2 = JSON.stringify(res)
                        console.log(json2);
                    })
                    console.log(typeof xhr.responseText + ':' + xhr.response);
                    console.log(JSON.parse(xhr.response));
                }
            }
        })

URL编码

 var bian = encodeURI('你的')
            var jie = decodeURI('%E4%BD%A0%E5%A6%88%E9%80%BC')
            console.log(bian, jie);

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值