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】Android内存机制,了解Android堆和栈
1.dalvik的Heap和Stack 这里说的只是dalvik java部分的内存,实际上除了dalvik部分,还有native. 下面针对上面列出的数据类型进行说明,只有了解了我们申请的数 ...
- [Java拾遗一] XML的书写规范与解析.
前言今天天气大好, 起了个大早开始总结一些常用的基础知识. XML一直来说都很陌生, 使用大多是用于配置文件, 之前并没有细究过其中的约束规范, 今天刚好没事来学习并总结下. 1,XML基础介绍 XM ...
- JAVA学习Swing章节流布局管理器简单学习
package com.swing; import java.awt.Container; import java.awt.FlowLayout; import javax.swing.JButton ...
- EndPoint详解
EndPoint详解 EndPoint主要用于暴露一些SpringMvc内部运行的信息,通常是通过SpringMvc的请求地址获取相关信息.如/health获取健康检查信息. 简单单元测试 @Test ...
- VC基于消息的异步套接字
用WSAStartup,需要在StdAfx.h头文件中需要声明 #include #pragma comment(lib,"WS2_32.lib") 用AfxSocket ...
- Swift开发iOS应用过程中的问题和解决记录
虚拟机里安装OSX+XCode开发环境 用真机的请直接跳过这个部分. 主要是在VitrualBox里安装mac系统和xcode,参考这篇教程,VirtualBox的版本是4.3.18 r96156,O ...
- TableView didSelectRowAtIndexPath 不执行
1.父类事件设置代理 UIGestureRecognizer *tapGesture ... tapGesture.delegate = self; 2.覆盖方法 - (BOOL)gestureRe ...
- spring-boot 加载本地静态资源文件路径配置
1.spring boot默认加载文件的路径是 /META-INF/resources/ /resources/ /static/ /public/ 这些目录下面, 当然我们也可以从spring bo ...
- Android webView打不开网页的解决办法
在我们开发过程中,有可能会遇到webview有些网页打不开的问题.这可能是设置的不对,下面就是解决办法. 进行如下设置吧,大多数情况都能解决! displayWebview.getSettings() ...
- ReactiveCocoa与Functional Reactive Programming
转自 http://blog.leezhong.com/ios/2013/06/19/frp-reactivecocoa.html Functional Reactive Programming(以下 ...