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. ...
随机推荐
- windows下使用批处理脚本实现多个版本的JDK切换
一.JDK版本切换批处理脚本 我们平时在window上做开发的时候,可能需要同时开发两个甚至多个项目,有时不同的项目对JDK的版本要求有区别,这时候我们可能会在一台电脑上安装多个版本的JDK,如下图所 ...
- UTL_FILE建文件失败“ORA-29280: 目录路径无效”错误
存储过程写文件需要配置可写的目录,具体是utl_file_dir这个参数,把UTL_FILE输出的目录写到这个参数,如果不限制,可以令utl_file_dir=* 查看: SQL> sh ...
- MVP
引自: http://www.cnblogs.com/Leo_wl/archive/2013/05/03/3056299.html http://www.codeproject.com/Article ...
- java 连接 MySQL
java 连接 MySQL 1.准备工作 需要下载的工具: MySQL:http://www.mysql.com/downloads/ MySQL的可视化工具SQLyog:https://www.we ...
- [JS] HTML QQ分享界面js代码
@ - @ :可以自己指定分享内容等....内含JS脚本 <html> <head> <title></title> <script type=& ...
- 使用SharePoint CSOM 编写高效的程序
上一篇文章中简单的介绍了使用CSOM进行编程.今天主要讲一下CSOM使用中一些小技巧,可以让你的程序运行的更快. 单独加载某些属性 在上文中的例子,需要返回Web对象信息的时候,我们使用了如下的代码: ...
- JETTY嵌入式Web容器的开发
JETTY嵌入式Web容器的开发 JETTY嵌入式Web容器体积小,启动速度快,性能好,免费开源,是一款很适合开发调试和简单演示的轻量级Web容器. 而且它的嵌入式的特点,使得开发者可以直接将容器的操 ...
- atitit.html5 拼图游戏的解决之道.
atitit.html5 拼图游戏的解决之道. 1. 拼图游戏的操作(点击法and 拖动法) 1 1. 支持键盘上.下.左.右键移动: 1 2. 支持点击空白模块中的上下左右箭头移动: 1 3. 支持 ...
- Maven学习总结(二)——Maven项目构建过程练习_转载
上一篇只是简单介绍了一下maven入门的一些相关知识,这一篇主要是体验一下Maven高度自动化构建项目的过程 一.创建Maven项目 1.1.建立Hello项目 1.首先建立Hello项目,同时建立M ...
- IOS开发之进阶篇第一章 - 姿势识别器UIPanGestureRecognizer
今天讲一下姿势识别器,UIGestureRecognizer这个是抽象类 1.拍击UITapGestureRecognizer (任意次数的拍击) 2.向里或向外捏UIPinchGestureReco ...