原生js ajax与jquery ajax的区别

原生js ajax的调用:

ajax({
type : "get",
url : "02_ajax_get.txt",
data : {
"userName" : "lnj",
"userPwd" : "321"
},
timeout : time, //超时时间
success : function (xmlhttp) {
alert(xmlhttp.responseText);
},
error : function (xmlhttp) {
alert('请求失败!');
}
});


jquery ajax的调用:
$.ajax({
type : "get",
url : "02_ajax_get.txt",
data : "userName=lnj&userPwd=321",
   timeout : time, //超时时间
success : function (xmlhttp) {
alert(xmlhttp.responseText);
},
error : function (xmlhttp){
alert('请求失败!');
}
});


myajax.js 文件:
function obj2str(data) {
/*
{
"userName" : "Inj",
"userPwd" : "123456"
"t" : "3221312313123"
}
*/
data.t = new Date().getTime();
var res = [];
//for in 专门用来遍历对象的
//key(就是对象的属性), data[key](就是属性对应的属性值)
for(var key in data) {
//在URl中是不可以出现中文的,如果出现中文需要转码
//可以调用encodeURIComponent()方法
//URL中只可以出现字母/数字/下划线/ASCII码(其他的都需要转码)(%25E5%2593%2588%25E5%2593%25)
res.push(encodeURIComponent(key) + "=" + encodeURIComponent(data[key])); //[userName=Inj,userPwd=123456]
}
return res.join("&"); //userName=Inj&userPwd=123456
}
// 传入的参数为对象可以使调用对象里面的属性不用按着顺序来
function ajax(option) {
//将对象转换为字符串
var str = obj2str(option.data); //key=value&key=value
//1.创建一个异步对象
//var xmlhttp = new XMLHttpRequest();

//兼容IE5,IE6
var xmlhttp, timer;
if(window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

//2.设置请求方式和请求地址

/*
method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步)
*/
if(option.type.toLowerCase() == "GET") {
xmlhttp.open(option.type, option.url + "?" + str, true); //提交请求url地址不能出现中文
//3.发送请求
xmlhttp.send();
} else {
xmlhttp.open(option.type, option.url, true);

//注意点:必须放在open和send之间
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

xmlhttp.send(str);
}

//4.监听状态的变化
xmlhttp.onreadystatechange = function (ev2) {
/*
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
*/
if(xmlhttp.readyState == 4) {
clearInterval(timer);
//判断请求是否成功
if((xmlhttp.status >= 200 && xmlhttp.status < 300) || xmlhttp.status == 304) {//服务器返回的状态码
//5.处理返回的结果
option.success(xmlhttp);
} else {
option.error(xmlhttp);
}
}
}
//判断外界是否传入超时时间
if(option.timeout) {
timer = setInterval(function () {
console.log("中断请求");
xmlhttp.abort();//关闭请求
clearInterval(timer);
}, option.timeout);
}
}
 

猜你喜欢

转载自www.cnblogs.com/showcase/p/10435371.html