ajax-jquery的使用

$(function(){
	$("button").click(function (ev1) {
		$.ajax({
			type: "get",
			url: "ajax-jquery.php",
			data: {
				"userName": "123",
				"userPwd": "abc"
			},
			timeout:3000,
			success: function (msg) {
				alert("Data Saved: " + msg);
			},
			error: function (msg) {
				alert(msg.status);
			}
		});
	})
});	

封装

function dataToStr(data){
	data.t = new Date().getTime();
	var res = [];
	for(var key in data){
		// 在url中是不可以出现中文的,如果出现了中文需要转码
		// url中只能出现数字/字母/下划线/ASCLL码
		res.push(encodeURIComponent(key) + "=" +encodeURIComponent(data[key]));
	}
	return res.join("&");
}

function ajax(option) {
	// 0. 将对象转换成字符串
	var str = dataToStr(option.data);
	// 1.创建一个异步对象
	var xmlhttp,timer;
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (option.type.toLowerCase() === 'get'){
		// 2.设置请求方式和请求地址
		xmlhttp.open(option.type, option.url+"?"+str, true);
		// 3.发送请求
		xmlhttp.send();
	} else{
		xmlhttp.open(option.type, option.url, true);
		xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlhttp.send(str);
	}
	// 4.监听状态的变化
	xmlhttp.onreadystatechange = function (ev2) {
		// 判断是否响应就绪
		if (xmlhttp.readyState === 4) {
			// 判断是否请求成功
			if (xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status === 304) {
				// 5.处理返回的结果
				option.success(xmlhttp);
			} else {
				// 5.处理返回的结果
				option.error(xmlhttp);
			}
		}
	}
	// 判读外界是否传入了超时时间
	if (option.timeout){
		timer = setInterval(function(){
			// console.log("中断请求");
			xmlhttp.abort();
			clearInterval(timer);
		}, option.timeout);
	}
}
window.onload = function (e) {
	var oBtn = document.querySelector("button");
	oBtn.onclick = function (ev1) {
		ajax({
			type: "get",
			url: "ajax-jquery.php",
			data: {
				"userName": "123",
				"userPwd": "abc"
			},
			timeout: 3000,
			success: function (msg) {
				alert(msg.responseText);
			},
			error: function (msg) {
				alert(msg.status);
			}
		});
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值