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>
JavaScript封装Ajax(类JQuery中$.ajax()方法)的更多相关文章
- 封装一个类似jquery的ajax方法
		
//封装一个类似jquery的ajax方法,当传入参数,就可以发送ajax请求 //参数格式如下{ // type:"get"/"post", // dataT ...
 - JS原生ajax与Jquery插件ajax深入学习
		
序言: 近来随着项目的上线实施,稍微有点空闲,闲暇之时偶然发现之前写的关于javascript原生xmlHttpRequest ajax方法以及后来jquery插件ajax方法,于是就行了一些总结,因 ...
 - js原生ajax与jquery的ajax的用法区别
		
什么是ajax和原理? AJAX 是一种用于创建快速动态网页的技术. 通过XmlHttpRequest对象来向服务器发异步请求,从服务器获得数据 XMLHttpRequest对象的基本属性: onre ...
 - CSIC_716_20191127【组合,封装、类的私有属性方法、property装饰器】
		
组合 what? 组合是指一个对象中,包含另一个或多个对象. why? 减少代码的冗余. How? 在类中加入其他类的对象,实现跨类对象之间的联动. 耦合度 软件设计要 高内聚 ...
 - 通过原生js的ajax或jquery的ajax获取服务器的时间
		
在实际的业务逻辑中,经常是与时间相关的,而前端能获得的时间有两个:客户端的时间,服务器的时间. 客户端时间通过 javascript中的Date对象可以获取,如 var dt = new Date() ...
 - AJAX初识(原生JS版AJAX和Jquery版AJAX)
		
一.什么是JSON 1.介绍 JSON独立于语言,是一种与语言无关的数据格式. JSON指的是JavaScript对象表示法(JavaScript Object Notation) JSON是轻量级的 ...
 - 原生js实现ajax与jquery的ajax库,及json
		
这是一篇笔记博客, Ajax: 和服务器进行数据交换(异步) 用js实现复杂的原理:用于发送请求的对象在不同的浏览器中是不同的 同源策略:ajax发送请求的url地址与服务器地址必须是同一域名,协议, ...
 - javascript : 写一个类似于 jquery css() 的方法
		
我们知道,jquery css() 方法可以很方便的更改DOM的样式. 但从原理上,这个并不复杂,我们完全可以自己写一个. 上代码. updateDOMStyle(DOM, obj){ Object. ...
 - JavaScript封装成类
		
JavaScript在WEB编程中能起到很大的作用,将一些常用的功能写成JavaScript类库. 将下面代码保存为Common.js 类库功能: 1.Trim(str)--去除字符串两边的空格 2. ...
 
随机推荐
- Android-Universal-Image-Loader三大组件DisplayImageOptions、ImageLoader、ImageLoaderConfiguration详解
			
一.介绍 Android-Universal-Image-Loader是一个开源的UI组件程序,该项目的目的是提供一个可重复使用的仪器为异步图像加载,缓存和显示.所以,如果你的程序里需要这个功能的话, ...
 - SQL Server 2014 安装小记
			
一.写在前面 由于想体验下微软的Windows Azure在SQL Server数据库方面的使用,笔者花了点时间安装了一下SQL Server 2014,安装很简单,基本就是稍微做些配置即可,笔者在此 ...
 - Windows Server 2008R2 配置网络负载平衡(NLB)
			
目录 配置环境 安装 安装网络负载平衡 安装Web服务器 IIS 配置 测试 其它 配置环境 VMware:(版本10.0.01) 主集群IP:192.168.220.102 VM1:192.168. ...
 - 两两组合覆盖测试用例设计工具:PICT
			
两两组合覆盖测试用例设计工具:PICT 2016-08-31 目录 1 成对测试简介2 PICT使用 2.1 安装 PICT 2.2 使用PICT3 PICT算法 3.1 准备阶段 3.2 产 ...
 - JavaScript核心编程(代码片段)
			
var a = function () { function someSetup() { var setup = 'done'; } function actualWork() { alert('Wo ...
 - javaweb回顾第四篇Servlet异常处理
			
前言:很多网站为了给用户很好的用户体验性,都会提供比较友好的异常界面,现在我们在来回顾一下Servlet中如何进行异常处理的. 1:声明式异常处理 什么是声明式:就是在web.xml中声明对各种异常的 ...
 - docker使用GPU
			
1.物理机安装显卡驱动 2.安装nvidia-docker wget -P /tmp https://github.com/NVIDIA/nvidia-docker/releases/download ...
 - 如何在windows7上安装启明星系统。
			
启明星系统提供多种安装方式.安装包里自带了setup.exe.每个程序的 install下有在线安装(例如请假应用程序为book,则默认为 http://localhost/book/install ...
 - RFID 基础/分类/编码/调制/传输
			
不同频段的RFID产品会有不同的特性,本文详细介绍了无源的感应器在不同工作频率产品的特性以及主要的应用. 目前定义RFID产品的工作频率有低频.高频和甚高频的频率范围内的符合不同标准的不同的产品,而且 ...
 - 内存缓存LruCache实现原理
			
自己项目中一直都是用的开源的xUtils框架,包括BitmapUtils.DbUtils.ViewUtils和HttpUtils四大模块,这四大模块都是项目中比较常用的.最近决定研究一下xUtils的 ...