原生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);
}
}

本人正在學習和摸索中,如有錯誤,歡迎指正!
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM