1. 程式人生 > >ajax封裝函數和表單序列化

ajax封裝函數和表單序列化

part TP function dex ++ elements get 不支持 callback


//表單序列化
function iSerialize(form){
var parts={};
for(var i=0;i<form.elements.length;i++){
var filed=form.elements[i];
switch(filed.type){
case undefined:
case "submit":
case "reset":
case "file":
case "button":
break;
case "radio":
case "checkbox":
if(!filed.selected) break;
case "select-one":
case "select-multiple":
for(var j=0;j<filed.options.length;j++){
var option=filed.options[j];
if(option.selected){
var optValue="";
if(option.hasAttribute){
optValue=(option.hasAttribute("value")?option.value:option.text);
}else{
optValue=(option.attributes("value").specified?option.value:option.text);
}
parts[filed.name]=optValue;
}
}
break;
default:
parts[filed.name]=filed.value;
}
}
return parts;
}

//封裝ajax
function iAjax(obj) {
var xhr = (function () {
if (typeof XMLHttpRequest != ‘undefined‘) {
return new XMLHttpRequest();
} else if (typeof ActiveXObject != ‘undefined‘) {
var version = [
‘MSXML2.XMLHttp.6.0‘,
‘MSXML2.XMLHttp.3.0‘,
‘MSXML2.XMLHttp‘
];
for (var i = 0; version.length; i ++) {
try {
return new ActiveXObject(version[i]);
} catch (e) {
//跳過
}
}
} else {
throw new Error(‘您的系統或瀏覽器不支持XHR對象!‘);
}
})();
obj.url = obj.url + ‘?rand=‘ + Math.random();
obj.data = (function (data) {
var arr = [];
for (var i in data) {
arr.push(encodeURIComponent(i) + ‘=‘ + encodeURIComponent(data[i]));
}
return arr.join(‘&‘);
})(obj.data);
if (obj.method === ‘get‘) obj.url += obj.url.indexOf(‘?‘) == -1 ? ‘?‘ + obj.data : ‘&‘ + obj.data;
if (obj.async === true) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
callback();
}
};
}
xhr.open(obj.method, obj.url, obj.async);
if (obj.method === ‘post‘) {
xhr.setRequestHeader(‘Content-Type‘, ‘application/x-www-form-urlencoded‘);
xhr.send(obj.data);
} else {
xhr.send(null);
}
if (obj.async === false) {
callback();
}
function callback() {
if (xhr.status == 200) {
obj.success(xhr.responseText); //回調傳遞參數
} else {
alert(‘獲取數據錯誤!錯誤代號:‘ + xhr.status + ‘,錯誤信息:‘ + xhr.statusText);
}
}
}

ajax封裝函數和表單序列化