专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > jQuery

JavaScript打包Ajax(类JQuery中$.ajax()方法)

发布时间:2010-05-20 14:01:29 文章来源:www.iduyao.cn 采编人员:星星草
JavaScript封装Ajax(类JQuery中$.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>

 

友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

  • jQuery搜索框输入文字下拉揭示菜单

    jQuery搜索框输入文字下拉提示菜单 jQuery搜索框输入文字下拉提示菜单 原文地址: http://www.jq22.com/jquery-info6193 ...

  • 7个替开发者准备的有用的jQuery技巧

    7个为开发者准备的有用的jQuery技巧 一、在新窗口打开链接 用下面的代码,你点击链接即可在新窗口打开: $(document).ready(fu...

  • jQuery获取呼应Input例子

    jQuery获取相应Input例子 页面上有许多input框,使用的是EasyUI样式,中间还参杂着各种其他无id的Input框,如下: <input class=...

  • webpack 引出jquery和第三方jquery插件

    webpack 引入jquery和第三方jquery插件 1、引入jquery jQuery 直接在 html 中引入,然后在 webpack 中把它配置为全局即可。 index....

  • JQuery的开发与使用经验

    JQuery的开发与使用心得 关于jQuery的 入门使用jQuery可以很容易或具有挑战性的,这取决于你如何使用JavaScript,HTML,CSS进行开发和...

  • 深入学习jQuery卡通片控制

    深入学习jQuery动画控制 &times; 目录 [1]动画状态 [2]停止动画 [3]动画延迟[4]全局控制 前面的话   jQuery动画可以使用fade、...

  • jquery操作table报表

    jquery操作table表格 一、数据准备 <table id="table1"> <tr><th>文章标题</th><th>文章分类</th><th>发布时间</th><th>...

  • html + css + jquery实现简略的进度条实例

    html + css + jquery实现简单的进度条实例 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-eq...

  • jquery中ajax方法的datatype的功用

    jquery中ajax方法的datatype的作用 今天在维护一个项目的时候遇见了一个小问题。但是这个问题我认为对于项目十分有帮助。...

  • jQuery菜单示范(全选,反选,取消)

    jQuery菜单示例(全选,反选,取消) 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <titl...

热门推荐: