吃饭用的前端

Ajax的封装和FormData的使用

2019-05-24  本文已影响0人  CNLISIYIII

(一)$ajax

1.已封装好的ajax:
2.常用参数:

代码举栗:

<body>
    <p id="loading" style="display: none">玩命加载中...</p>
    <script src="lib/jquery-1.12.4.js"></script>
    <script>
        $.ajax({
            //请求方式,默认是get
            type: 'GET',
            //URL 请求地址
            url: '/big-data',
            //发送给服务器的参数(可选,可以是字符串或者对象)
            data: 'id=11&age=22&sex=33',
            //处理服务器返回的数据
            success: function(result) {
                //result就是服务器返回的数据
                console.log(result); 
                //返回一个object{id:11,age:22,sex:33}
            }
            //发送请求开始时
            beforeSend: function() {
                $('#loading').show();
            },
            //请求结束后
            complete: function() {
                $('#loading').hide();
            }
            //把data对象转成字符串
            processData: false
        })
    </script>
</body>

3.GET和POST快捷方法

$.get(url, [data], [callback], [dataType])
$.post(url, [data], [callback], [dataType])
属性url必须写,其他可选。

代码举栗:

        $.get('/time', function(result) {
            console.log(result);
        });

4.全局事件

语法:$.ajaxSetup({事件: 处理函数, 事件:处理函数, ...});

代码举栗:

<body>
    <input type="button" value="请求">
    <p id="loading" style="display: none">玩命加载中...</p>
    <script src="lib/jquery-1.12.4.js"></script>
    <script>
        //注册全局事件,后续每次Ajax请求都会自动触发全局事件
        $.ajaxSetup({
            beforeSend: function () {
                $('#loading').show();
            },
            complete: function () {
                $('#loading').hide();
            }
        });
        //如果有很多ajax请求,每一个请求都需要一个提示
        $.ajax({
            url: '/big-data',
            success: function (result) {
                console.log(result.length);
            }
        })
        //点击按钮的时候再次发生ajax请求
        $('input').click(function () {
            $.ajax({
                url: '/big-data',
                success: function (result) {
                    console.log(result.length);
                }
            })
        })
    </script>
</body>

进度提示插件:* https://github.com/rstacruz/nprogress

(二)XMLHttpRequest

1.responseType / response

代码举栗:

        var xhr = new XMLHttpRequest();
        xhr.open('get', '/query-get?id=1&age=2');
        // responseType要放到send前面
        xhr.responseType = 'json';
        xhr.send();
        xhr.onload = function () {
            // response会根据responseType指定的类型自动处理结果
            console.log(this.response);
        }

2.onload / onprogress

代码举栗:

        var xhr = new XMLHttpRequest()
        xhr.open('GET', '/time')
        xhr.onload = function () {
            // onload readyState => 4
            // 只在请求完成时触发
            console.log(this.readyState)
        }
        xhr.onprogress = function () {
            // onprogress readyState => 3
            // 只在请求进行中触发
            console.log(this.readyState)
        }
        xhr.onloadstart = function () {
            // onloadstart readyState => 1
            // 开始发送请求的时候触发
            console.log(this.readyState)
        }
        xhr.onloadend = function () {
            // onloadend readyState => 4
            // 请求响应过程结束的时候触发
            console.log(this.readyState)
        }
        xhr.send(null)

3.FormData

使用FormData收集表单数据提交给服务器,一定要选择POST方式,且必须省略xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');这行代码。

有form表单时代码举栗:

<body>
    <form id="fm">
        <input type="text" name="user">
        <br>
        <input type="password" name="pwd">
        <br>
        <input type="radio" name="sex" value="男" checked>男
        <input type="radio" name="sex" value="女">女
        <br>
        <input type="file" name="pic">
        <br/>
        <input type="button" id="btn" value="提交">
    </form>
    <script>
        document.getElementById('btn').onclick = function () {
            //找到表单DOM对象
            var fm = document.getElementById('fm');
            // 创建FormData对象并传递表单
            var fd = new FormData(fm);
            var xhr = new XMLHttpRequest();
            //接口fd:收到提交的数据后会返回收到的数据
            xhr.open('POST', '/fd');
            xhr.responseType = 'json';
            // xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send(fd);
            xhr.onload = function () {
                console.log(this.response);
            }
        }
    </script>
</body>

没有form表单时代码举栗:

<body>
    <input type="text" name="user"><br>
    <input type="password" name="pwd"><br>
    <input type="file" name="pic"><br/>
    <input type="button" id="btn" value="提交">
    <script>
        document.getElementById('btn').onclick = function () {
            //实例化FormData对象
            var fd = new FormData();
            //调用内置对象FormData中自带的方法:append追加
            fd.append('username', document.getElementById('user').value);
            fd.append('password', document.getElementById('pwd').value);
            var f = document.getElementById('pic');
            var fileObj = f.fileObj[0];
            fd.append('myfile', fileObj);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/fd');
            xhr.responseType = 'json';
            xhr.send();
            xhr.onload = function () {
                console.log(this.response);
            }
        }
    </script>
</body>

使用FormData时要传对象而不是字符串。
jQuery中使用FormData代码举栗:

<body>
    <input type="text" name="user"><br>
    <input type="password" name="pwd"><br>
    <input type="file" name="pic"><br/>
    <input type="button" id="btn" value="提交">
    <script src="lib/jquery-1.12.4.js"></script>
    <script>
        $('$btn').click(function () {
            //使用FormData收集表单信息
            var fd = new FormData(document.getElementById('fm'));
            $.ajax({
                type: 'POST',
                url: '/fd',
                data: fd,
                //表示不让jQuery将fd对象处理成字符串,应该直接使用fd对象
                processData: false,
                //使用FormData时不能设置Content-Type,让FormData自己处理,所以改成false
                contentType: false,
                success: function (result) {
                    console.log(result);
                }
            })
        })
    </script>
</body>
上一篇 下一篇

猜你喜欢

热点阅读