JavaScript封裝Ajax(類JQuery中$.ajax()方法)

來源:互聯網
上載者:User

標籤:javascript   ajax   

ajax.js

(function(exports, document, undefined){    "use strict";    function Ajax(){        if(!(this instanceof Ajax)) return;        return this;    }    Ajax.prototype = {        init: function(opts){            opts = opts || {};            this.opts = opts;            this.opts.type = opts.type || ‘get‘;            this.opts.url = opts.url || ‘‘;            this.opts.data = opts.data || ‘‘;            this.opts.dataType = opts.dataType || ‘text‘;            this.opts.async = opts.async || true;            this.opts.success = opts.success || null;            this.opts.error = opts.error || null;            this.xhr = this.createXMLHttpRequest.call(this);            this.initEvent.call(this);            return this;        },        ajax: function(opts){            this.init.apply(this, arguments);            this.open.call(this);            this.send.call(this);        },        createXMLHttpRequest: function(){            var xhr;            try{                xhr = new XMLHttpRequest();            }catch(e){                console.log(e);            }            return xhr;        },        initEvent: function(){            var _this = this;            this.xhr.onreadystatechange = function(){                if(_this.xhr.readyState == 4 && _this.xhr.status == 200){                    if(_this.xhr.status == 200){                        if(_this.opts.dataType === ‘text‘ || _this.opts.dataType === ‘TEXT‘){                            _this.opts.success && _this.opts.success(_this.xhr.responseText, ‘success‘, _this.xhr);                        }else if(_this.opts.dataType === ‘xml‘ || _this.opts.dataType === ‘XML‘){                            _this.opts.success && _this.opts.success(_this.xhr.responseXML, ‘success‘, _this.xhr);                        }else if(_this.opts.dataType === ‘json‘ || _this.opts.dataType === ‘JSON‘){                            _this.opts.success && _this.opts.success(JSON.parse(_this.xhr.responseText), ‘success‘, _this.xhr);                        }                    }else if(_this.xhr.status != 200){                        _this.opts.error && _this.opts.error(_this.xhr, ‘error‘);                    }                }            }        },        open: function(){            if(this.opts.type === ‘GET‘ || this.opts.type === ‘get‘){                var str = (typeof this.opts.data === ‘string‘) && this.opts.data || this.objectToString.call(this, this.opts.data),                    url = (str === ‘‘) && this.opts.url || (this.opts.url.split(‘?‘)[0] + ‘?‘ + str);                this.xhr.open(this.opts.type, url, this.opts.async);            }else if(this.opts.type === ‘POST‘ || this.opts.type === ‘post‘){                this.xhr.open(this.opts.type, this.opts.url.split(‘?‘)[0], this.opts.async);            }            return this;        },        send: function(){            if(this.opts.type === ‘GET‘ || this.opts.type === ‘get‘){                this.xhr.send();            }else if(this.opts.type === ‘POST‘ || this.opts.type === ‘post‘){                var str = (typeof this.opts.data === ‘string‘) && this.opts.data || this.objectToString.call(this, this.opts.data);                this.xhr.setRequestHeader(‘content-type‘, ‘application/x-www-form-urlencoded‘);                this.xhr.send(str);            }        },        objectToString: function(data){            if(typeof data !== ‘object‘) return data;            var str = ‘‘;            for(var prop in data){                str += ‘&‘ + prop + ‘=‘ + data[prop];            }            return str.slice(1);        }    }    exports.Ajax = Ajax;})(window, document);

ajax.php

<?php$c = $_REQUEST[‘c‘];$arr = array(    ‘a‘=>2014,    ‘b‘=>array(‘c‘=>$c));echo json_encode($arr);

index.html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>ajax</title></head><body>    <script src="ajax.js"></script>    <script>        new Ajax().ajax({            type: ‘get‘,            url: ‘ajax.php?c=123‘,      // 如果是get方式並且url包含參數,其參數會被data替代            // data: ‘c=456‘,           // data參數格式可以為字串或對象            // data: {c: 456},            dataType: ‘json‘,            async: false,            success: function(data, status, xhr){                console.log(data);            },            error: function(xhr, status){                console.log(xhr);            }        });        new Ajax().ajax({            type: ‘post‘,            url: ‘ajax.php?c=123‘,      // 如果是get方式並且url包含參數,其參數會被data替代            data: ‘c=456‘,              // data參數格式可以為字串或對象            // data: {c: 456},            dataType: ‘text‘,            success: function(data, status, xhr){                console.log(data);            },            error: function(xhr, status){                console.log(xhr);            }        });    </script></body></html>

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

JavaScript封裝Ajax(類JQuery中$.ajax()方法)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.