码迷,mamicode.com
首页 > Web开发 > 详细

Ajax的封装。

时间:2017-06-19 20:57:45      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:params   hang   content   send   response   ajax   服务端   调用   pre   

封装 Ajax

因为Ajax 使用起来比较麻烦,主要就是参数问题,比如到底使用GET 还是POST;到

底是使用同步还是异步等等,我们需要封装一个Ajax 函数,来方便我们调用。

   封装支持接收来自服务端的数据,不可以发送数据到服务端

/**

* 此封装只支持接收来自服务端的数据,不可以发送数据到服务端

 */

function ajax(obj) {

    var xhr = new XMLHttpRequest();

    obj.url = obj.url + ‘?rand=‘ + Math.random();

    xhr.open(obj.method, obj.url, obj.async);

    xhr.send(null);

    if (obj.async === false) {

        callback();

    }

    if (obj.async === true) {

        xhr.onreadystatechange = function () {

            if (xhr.readyState == 4) {

                callback();

            }

        };

    }

    function callback () {

        if (xhr.status == 200) {

            obj.success(xhr.responseText); //回调

        } else {

            alert(‘数据返回失败!状态代码:‘ + xhr.status + ‘,状态信息:‘ + xhr.statusText);

        }

    }

}

  

   把上面的代码封装在ajax2.js中,在页面上引入该文件。

<!DOCTYPE html>

<html>

<head>

    <title>Ajax的封装</title>

    <meta charset="utf-8">

    <script src="ajax2.js"></script>

</head>

<body>

<button id="btn">调用Ajax</button>

<script>

    document.getElementById("btn").onclick=function(){

        ajax({

            method : ‘get‘,

            url : ‘http://localhost:3000/api/2‘,

            success : function (text) {

                alert(text);

            },

            async :false

        });

    };

</script>

</body>

</html>

7.2  封装支持接收来自服务端的数据,又可以发送数据到服务端

function ajax(obj) {

    var xhr = new XMLHttpRequest();

    obj.url = obj.url + ‘?rand=‘ + Math.random();

    obj.data = params(obj.data);

    if (obj.method === ‘get‘) {

        obj.url = obj.url.indexOf(‘?‘) == -1 ? obj.url + ‘?‘ + obj.data : obj.url + ‘&‘ + obj.data;

    }

 

    if (obj.async === true) {

        xhr.onreadystatechange = function () {

            if (xhr.readyState == 4) {

                callback();

            }

        };

    }

    xhr.open(obj.method, obj.url, obj.async);

    if (obj.method === ‘post‘) {

        xhr.setRequestHeader(‘Content-Type‘, ‘application/x-www-form-urlencoded‘);

        xhr.send(obj.data);

    } else {

        xhr.send(null);

    }

    if (obj.async === false) {

        callback();

    }

    function callback () {

        if (xhr.status == 200) {

            obj.success(xhr.responseText); //回调

        } else {

            alert(‘数据返回失败!状态代码:‘ + xhr.status + ‘,状态信息:‘ + xhr.statusText);

        }

    }

}

 

//名值对编码

function params(data) {

    var arr = [];

    for (var i in data) {

        arr.push(encodeURIComponent(i) + ‘=‘ + encodeURIComponent(data[i]));

    }

    return arr.join(‘&‘);

}

          希望能够帮到你!

Ajax的封装。

标签:params   hang   content   send   response   ajax   服务端   调用   pre   

原文地址:http://www.cnblogs.com/nujufoul/p/7050382.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!