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()方法)的更多相关文章

  1. 封装一个类似jquery的ajax方法

    //封装一个类似jquery的ajax方法,当传入参数,就可以发送ajax请求 //参数格式如下{ // type:"get"/"post", // dataT ...

  2. JS原生ajax与Jquery插件ajax深入学习

    序言: 近来随着项目的上线实施,稍微有点空闲,闲暇之时偶然发现之前写的关于javascript原生xmlHttpRequest ajax方法以及后来jquery插件ajax方法,于是就行了一些总结,因 ...

  3. js原生ajax与jquery的ajax的用法区别

    什么是ajax和原理? AJAX 是一种用于创建快速动态网页的技术. 通过XmlHttpRequest对象来向服务器发异步请求,从服务器获得数据 XMLHttpRequest对象的基本属性: onre ...

  4. CSIC_716_20191127【组合,封装、类的私有属性方法、property装饰器】

    组合 what?   组合是指一个对象中,包含另一个或多个对象. why?      减少代码的冗余. How?     在类中加入其他类的对象,实现跨类对象之间的联动. 耦合度  软件设计要 高内聚 ...

  5. 通过原生js的ajax或jquery的ajax获取服务器的时间

    在实际的业务逻辑中,经常是与时间相关的,而前端能获得的时间有两个:客户端的时间,服务器的时间. 客户端时间通过 javascript中的Date对象可以获取,如 var dt = new Date() ...

  6. AJAX初识(原生JS版AJAX和Jquery版AJAX)

    一.什么是JSON 1.介绍 JSON独立于语言,是一种与语言无关的数据格式. JSON指的是JavaScript对象表示法(JavaScript Object Notation) JSON是轻量级的 ...

  7. 原生js实现ajax与jquery的ajax库,及json

    这是一篇笔记博客, Ajax: 和服务器进行数据交换(异步) 用js实现复杂的原理:用于发送请求的对象在不同的浏览器中是不同的 同源策略:ajax发送请求的url地址与服务器地址必须是同一域名,协议, ...

  8. javascript : 写一个类似于 jquery css() 的方法

    我们知道,jquery css() 方法可以很方便的更改DOM的样式. 但从原理上,这个并不复杂,我们完全可以自己写一个. 上代码. updateDOMStyle(DOM, obj){ Object. ...

  9. JavaScript封装成类

    JavaScript在WEB编程中能起到很大的作用,将一些常用的功能写成JavaScript类库. 将下面代码保存为Common.js 类库功能: 1.Trim(str)--去除字符串两边的空格 2. ...

随机推荐

  1. 【shell脚本】显示文件的偶数或奇数行

    # Dispaly the odd line. awk 'NR%2==1' file

  2. Lingo 做线性规划 - DEA

    Reference: <An Introduction to Management Science Quantitative Approaches to Decision Making, Rev ...

  3. paip.hql的调试故障排查流程总结

    paip.hql的调试故障排查流程总结 环境.myeclipse7.0 1 Hql的调试工具myeclipxe默认工具.../Hibernate8IDE 1 故障的排除方法overview 1 Hql ...

  4. paip.数据挖掘--导出词库 清理太长的iptcode

    paip.数据挖掘--导出词库 清理太长的iptcode 原来eng2atian的时候儿,有些cnchar无对眼的atian,走临时使用nonex代替... 而个,要不个那清理给挂了.. #keywo ...

  5. Observer模式

    拉模式. Observer实现了一种间接关系.可以向各种对象注册观察者.可以有效地管理依赖关系. 拉模式实现简单,且Subject和Observer可以成为类库中的可重用元素. 当被观察对象比较复杂, ...

  6. 已知2个一维数组:a[]={3,4,5,6,7},b[]={1,2,3,4,5,6,7};把数组a与数组b 对应的元素乘积再赋值给数组b,如:b[2]=a[2]*b[2];最后输出数组b的元素。

    package hanqi; import java.util.Scanner; public class Test7 { public static void main(String[] args) ...

  7. Oracle数据库恢复

    建用户 wf2014 赋权限 grant dba to wf2014; 数据恢复 imp wf2014/wf2014 file=D:\wf2014.dmp full=y 参数设置: datasourc ...

  8. 如何关闭Linux里边的selinux ?

    原文地址: http://jingyan.baidu.com/article/6d704a131ba67828da51ca73.html 有很多的Linux使用者因为对selinux不熟悉,所以都会将 ...

  9. Could not find a storyboard named 'Main' in bundle NSBundle

    转自:http://www.cnblogs.com/ygm900/p/3836580.html 1.删掉工程中main.storyboard 后要删除plist文件中对应的键值,否则会报如下错误: C ...

  10. MRBS, meeting room manager system,会议预定管理系统

    MRBS,会议管理软件,新增权限控制,周期性例会管理等. 下载地址 http://www.dotnetcms.org/mrbs/mrbs.rar