用JS写的一个Ajax库(实例代码)


Posted in Javascript onAugust 06, 2016

myajax是一个用js编写的一个跨浏览器的ajax库,支持get, post, jsonp请求,精巧,简单。

一、发送GET请求:

myajax.get({
<span style="white-space:pre">	</span>data: {}, //参数
	url: "", //请求地址
	//发生错误是调用
	error: function(data) {
	},
	//请求成功调用
	success: function(data){		
<span style="white-space:pre">	</span>//eval(data); 将字符串转换成json
	}
});

二、发送POST请求:

myajax.post({
	data: {}, //参数
	url: "", //
	//发生错误是调用
	error: function(data) {
	},
	//请求成功调用
	success: function(data){
	//eval(data); 将字符串转换成json
	}
});

三、发送JSONP请求:

myajax.getJSONP({
//参数
data: {
},
url: "", //请求地址
//请求成功调用
success: function(data) {
},
//发生错误时调用
error: function() {
}
});

源码:

var myajax = {

	post: function(params){
		var xmlhttp = this.createXMLHttpRequest();
		if (xmlhttp != null)
		{
			var async = true;
			if (typeof params.async != "undefined")
				async = params.async;
			var data = null;
			if (typeof params.data != "undefined")
				data = params.data;
			var url = "";
			if (typeof params.url != "undefined")
				url = params.url;
			if (url == null || url.length == 0)
				return;
			xmlhttp.open("POST", url, async);
			if (async){
				xmlhttp.onreadystatechange = function(){
				
					if (this.readyState==4){
						if (this.status==200){

							if (typeof params.success != "undefined") {
								params.success(xmlhttp.responseText);
							}
						}
						else {
							if (typeof params.error != "undefined") {
								params.error(xmlhttp.status + xmlhttp.statusText);
							}
							console.error(url + ": " + xmlhttp.status);
						}
					}
				};
			}
			
			xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			var param = "";
			for (var prop in data) {
				param += prop + "=" + data[prop] + "&";
			}
			param = param.substring(0, param.length - 1);
			xmlhttp.send(param);
			if (!async) {
				
				if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
		
					if (typeof params.success != "undefined") {
						params.success(xmlhttp.responseText);
					}
				else {
					if (typeof params.error != "undefined") {
						params.error(xmlhttp.status + xmlhttp.statusText);
					}
					console.error(url + ": " + xmlhttp.status);
				}
				
			}
		}
	},
	get: function(params){
		var xmlhttp = this.createXMLHttpRequest();
		if (xmlhttp != null)
		{
			var async = true;
			if (params.async != undefined)
				async = params.async;
			var url = "";
			if (params.url != undefined)
				url = params.url;
			if (url == null || url.length == 0)
				return;
			if (params.data != null) {
				var data = params.data;
				var paramPrefix = url.indexOf("?") == -1 ? "?" : "&";
		
				url = url + paramPrefix;
				for (var prop in data) {
					url += prop + "=" + data[prop] + "&";
				}
				url = url.substring(0, url.length - 1);
			}
			xmlhttp.open("GET", url, async);
			if (async){
				xmlhttp.onreadystatechange = function(){
					if (this.readyState==4){
						if (this.status==200){
							if (typeof params.success != "undefined") {
								params.success(xmlhttp.responseText);
							}
						}
						else {
							if (typeof params.error != "undefined") {
								params.error(xmlhttp.status + xmlhttp.statusText);
							}
							console.error(url + ": " + xmlhttp.status);
						}
					}
				};
			}

			xmlhttp.send(null);
			if (!async) {
				if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
					if (typeof params.success != "undefined") {
						params.success(xmlhttp.responseText);
					}
				else {
					if (typeof params.error != "undefined") {
						params.error(xmlhttp.status + xmlhttp.statusText);
					}
					console.error(url + ": " + xmlhttp.status);
				}
						
				
			}
		}
	},
	createXMLHttpRequest: function(){
		if (window.XMLHttpRequest)
		{
			return new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
		{
		//code for IE5 and IE6
			return new ActiveXObject("Microsoft.XMLHTTP");
		}
		return null;
	},
	getJSONP: function(params) {

		var url = null;
		if (typeof params.url != "undefined") {
			url = params.url;
		}
		if (url == null) {
			return;
		}
		
		var ff = "" + new Date().getTime() + (parseInt(Math.random() * 10000000000));
		eval("jsonpCallback_" + ff + "=" + function(data){
	
			if (typeof params.success != "undefined") {
				params.success(data);
			}
		});

		//根据url中是否出现过 "?" 来决定添加时间戳参数时使用 "?" 还是 "&" 
		var paramPrefix = url.indexOf("?") == -1 ? "?" : "&";

		url = url + paramPrefix + "jsonpCallback=" + "jsonpCallback_" + ff;
		var param = "";

		if (typeof params.data != "undefined" && params.data != null) {
		
			var data = params.data;
			for (var prop in data) {
				param += prop + "=" + data[prop] + "&";
			}
			param = param.substring(0, param.length - 1);
		}
		if (param.length > 0)
		url = url + "&" + param; 
		var script = document.createElement("script"); 
		document.body.appendChild(script); 
		script.src = url; 
		script.charset ="UTF-8";
		// for firefox, google etc.
		script.onerror = function() {
			if (typeof params.error != "undefined") {
				params.error();
			}
			
	 	}
		script.onload = function() {

		document.body.removeChild(script); 
		} 
		// for ie 
		script.onreadystatechange = function() { 
		  if (this.readyState == "loaded" || this.readyState == "complete") { 
		    document.body.removeChild(script);
		  } 
		}
	}

};

以上这篇用JS写的一个Ajax库(实例代码)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
jquery DOM操作 基于命令改变页面
May 06 Javascript
javascript 当前日期转化为中文的实现代码
May 13 Javascript
向左滚动文字 js代码效果
Aug 17 Javascript
js jquery ajax的几种用法总结(及优缺点介绍)
Jan 28 Javascript
node.js中 stream使用教程
Aug 28 Javascript
javascript函数中的3个高级技巧
Sep 22 Javascript
JS实现的图片预览插件与用法示例【不上传图片】
Nov 25 Javascript
JS完成画圆圈的小球
Mar 07 Javascript
Node.js中.pfx后缀文件的处理方法
Mar 10 Javascript
详解weex默认webpack.config.js改造
Jan 08 Javascript
React路由管理之React Router总结
May 10 Javascript
Vue切换组件实现返回后不重置数据,保留历史设置操作
Jul 21 Javascript
angularJS 如何读写缓冲的方法(推荐)
Aug 06 #Javascript
JS获取和修改元素样式的实例代码
Aug 06 #Javascript
原生js获取元素样式的简单方法
Aug 06 #Javascript
浅析Node.js实现HTTP文件下载
Aug 05 #Javascript
JS中对Cookie的操作详解
Aug 05 #Javascript
jQuery插件EasyUI获取当前Tab中iframe窗体对象的方法
Aug 05 #Javascript
js实现精确到毫秒的倒计时效果
Aug 05 #Javascript
You might like
一个简单的PHP入门源程序
2006/10/09 PHP
PHP操作数组的一些函数整理介绍
2011/07/17 PHP
php简单实现MVC
2015/02/05 PHP
PHP四舍五入、取整、round函数使用示例
2015/02/06 PHP
浅谈php(codeigniter)安全性注意事项
2017/04/06 PHP
PHP用户注册邮件激活账户的实现代码
2017/05/31 PHP
PHP自定义函数判断是否为Get、Post及Ajax提交的方法
2017/07/27 PHP
PHP设计模式之装饰器模式实例详解
2018/02/07 PHP
获取dom元素那些讨厌的位置封装代码
2010/06/23 Javascript
30个经典的jQuery代码开发技巧
2014/12/15 Javascript
css如何让浮动元素水平居中
2015/08/07 Javascript
理解javascript中DOM事件
2015/12/25 Javascript
微信小程序 自定义对话框实例详解
2017/01/20 Javascript
JS实现基本的网页计算器功能示例
2020/01/16 Javascript
[01:15:00]LGD vs Mineski Supermajor 胜者组 BO3 第一场 6.5
2018/06/06 DOTA
Python实现SSH远程登陆,并执行命令的方法(分享)
2017/05/08 Python
Python实现的求解最大公约数算法示例
2018/05/03 Python
详解python Todo清单实战
2018/11/01 Python
python树莓派红外反射传感器
2019/01/21 Python
彻底理解Python中的yield关键字
2019/04/01 Python
python通过TimedRotatingFileHandler按时间切割日志
2019/07/17 Python
Python英文文章词频统计(14份剑桥真题词频统计)
2019/10/13 Python
介绍CSS3使用技巧5个
2009/04/02 HTML / CSS
Trunki英国官网:儿童坐骑式行李箱
2017/05/30 全球购物
澳大利亚首屈一指的鞋类品牌:Tony Bianco
2018/03/13 全球购物
应届生船舶驾驶求职信
2013/10/19 职场文书
师范大学音乐表演专业求职信
2013/10/23 职场文书
单位人事专员介绍信
2014/01/11 职场文书
教学器材管理制度
2014/01/26 职场文书
高中军训感言1000字
2014/03/01 职场文书
小区文明倡议书
2014/05/16 职场文书
乳制品整治工作方案
2014/05/29 职场文书
小学生推普周国旗下讲话稿
2014/09/21 职场文书
vue前端工程的搭建
2021/03/31 Vue.js
WINDOWS 64位 下安装配置mysql8.0.25最详细的教程
2022/03/22 MySQL
vue的项目如何打包上线
2022/04/13 Vue.js