//ajax相關腳本
var Ajax = {};
/**
* Ajax方法 該方法只適用於同步請求
*@param url: url路徑 參數可放在這裏也可放在para裏。
*@param para: 傳遞參數 可爲空, 不爲空時 通過sent傳值,可避ie下免傳參數過多導致失敗 參考:http://gbtan.iteye.com/blog/653314
*@return:json數據集或{"success":"false"}
*@demo:
1、var oJson = Ajax.post("abc.aspx?id=3");
2、var oJson = Ajax.post("abc.aspx","id=3");
*/
Ajax.post = function(url,para){
try{
var _para = para || null;
var NewXml;
if(window.ActiveXObject){
try{NewXml=new ActiveXObject("Microsoft.XMLHTTP");}
catch(e){
try{NewXml=new ActiveXObject("msxml2.XMLHTTP");}
catch(ex){}
}
}else if(window.XMLHttpRequest){
NewXml=new XMLHttpRequest();
}
NewXml.open("POST", url, false);
NewXml.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
NewXml.onreadystatechange = function(){
if (NewXml.readyState == 4){
if (NewXml.status == 200){
}else if (NewXml.status == 404){
alert("Request URL does not exist");
}else{
alert("Error: status code is " + NewXml.status);
}
}
};
NewXml.send(_para);
return eval('(' + NewXml.responseText + ')');
}
catch(e){
//alert(e.message);alert(e.description);alert(e.number);alert(e.name);
return{"success":"false"}
}
}
/**
* 執行基本ajax請求,返回XMLHttpRequest
* Ajax.Json(url,{
* async 是否異步 true(默認)
* method 請求方式 POST or GET(默認)
* data 請求參數 (鍵值對字符串或json對象) 例如: data : {name:'jack',age:20},
* success 請求成功後響應函數,參數爲json對象
* failure 請求失敗後響應函數,參數爲json對象
* });
*/
var myAjax = function(){
function Json(url,opt){
if(document.getElementById("_div_loging")==null){
_div_loging = document.createElement("div");
_div_loging.className = "loading";
_div_loging.innerHTML = "正在加載...";
_div_loging.id="_div_loging";
document.body.appendChild(_div_loging);
}
function fn(){}
var async = opt.async !== false,
method = opt.method || 'GET',
encode = opt.encode || 'UTF-8',
data = opt.data || null,
success = opt.success || fn,
failure = opt.failure || fn;
method = method.toUpperCase();
if(data && typeof data == 'object'){//對象轉換成字符串鍵值對
data = _serialize(data);
}
if(method == 'GET' && data){
url += (url.indexOf('?') == -1 ? '?' : '&') + data;
data = null;
}
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.onreadystatechange = function(){
_onStateChange(xhr,success,failure);
};
xhr.open(method,url,async);
if(method == 'POST'){
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=' + encode);
}
xhr.send(data);
return xhr;
}
function _serialize(obj){
var a = [];
for(var k in obj){
var val = obj[k];
if(val.constructor == Array){
for(var i=0,len=val.length;i<len;i++){
a.push(k + '=' + encodeURIComponent(val[i]));
}
}else{
a.push(k + '=' + encodeURIComponent(val));
}
}
return a.join('&');
}
function _onStateChange(xhr,success,failure){
if(xhr.readyState == 4){
var s = xhr.status;
if(s>= 200 && s < 300){
document.body.removeChild(document.getElementById("_div_loging"));
success(eval('(' + xhr.responseText + ')'));
}else{
failure(xhr);
}
}else{}
}
return {Json:Json};
}();
//將form元素按鍵值形式轉換成對象返回
function formToJSON(form){
var _json = '{';
var el;
for(var i = 0,len = form.elements.length;i < len;i++){
el = form.elements[i];
if(el.name == "" || el.disabled) continue;
switch(el.tagName.toLowerCase()){
case "fieldset":
break;
case "input":
switch(el.type.toLowerCase()){
case "radio":
if(el.checked)
_json+="\""+el.name+"\":\""+el.value+"\",";
break;
case "checkbox":
if(el.checked){
_json+="\""+el.name+"\":\""+el.value+"\",";
}
break;
case "button":
break;
case "image":
break;
default:
_json+="\""+el.name+"\":\""+el.value+"\",";
break;
}
break;
case "select":
if(el.multiple){
for(var j = 0, lens = el.options.length;j < lens; j++){
if(el.options[j].selected){
_json+="\""+el.name+"\":\""+el.options[j].value+"\",";
}
}
}else{
_json+="\""+el.name+"\":\""+el.value+"\",";
}
break;
default:
_json+="\""+el.name+"\":\""+el.value+"\",";
break;
}
}
form = el = null;
return _json.substring(0, _json.length - 1) + '}';
}
//根據id獲取對象
$=function(_id){
return document.getElementById(_id)?document.getElementById(_id):_id;
}
//根據name獲取對象
$$=function(_name){
return document.getElementsByName(_name)?document.getElementsByName(_name):_name;
}
/**
* 綁定select控件
*@param _selObj: 控件對象或
*@param _jsonObj: json數據集
*@param _text: 顯示字段
*@param _value: 值字段
*@return:true or false
*@throws 這個方法所拋出的異常
*/
fnBindSelect = function(_objSel,_jsonObj,_sText,_sValue){
_objSel=$(_objSel);
_objSel.options.length = 0;
if(_sText==null||_sText==""||_sValue==null||_sValue==""){ return false;}
if(_jsonObj.length == 0||_jsonObj==""){
_objSel.options[0] = new Option('===無===', '-1', 0, 0);
}else{
for (var i = 0; i < _jsonObj.length; i++) {
_objSel.options[i] = new Option(_jsonObj[i][_sText], _jsonObj[i][_sValue], 0, 0);
}
}
}
//js獲取url參數值 paras:參數名稱 如沒值則返回""
fnRequest = function(paras){
var url = location.href;
var paraString = url.substring(url.indexOf("?")+1,url.length).split("&");
var paraObj = {}
for (i=0; j=paraString[i]; i++){
paraObj[j.substring(0,j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=")+1,j.length);
}
var returnValue = paraObj[paras.toLowerCase()];
if(typeof(returnValue)=="undefined"){
return "";
}else{
return returnValue;
}
}
//js頁面跳轉 _url:網址
fnGetToUrl = function(_url){
window.location.href=_url;
}
//彈出對話框
fnShowDialog = function(_url){
window.open(_url);
}
//判斷字符串長度(中文爲2字節)
fucCheckLength = function(strTemp){
var i,sum=0;
for(i=0;i<strTemp.length;i++){
if ((strTemp.charCodeAt(i)>=0) && (strTemp.charCodeAt(i)<=255)){
sum=sum+1;
}else{
sum=sum+2;
}
}
return sum;
}
//判斷是否爲數字
function IsNum(s){
if (s!=null && s!="") {
return !isNaN(s);
}
return false;
}
/**
* 去字符串前後空格
*/
String.prototype.Trim = function(){
return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.LTrim = function(){
return this.replace(/(^\s*)/g, "");
}
String.prototype.RTrim = function(){
return this.replace(/(\s*$)/g, "");
}
/*** 動態加載圖片 ****/
//使用事例
//var img = new EnhancedImage(_localUrl + retJson.Dayinfo.item[tmpId].JP,onImageLoad);
//function onImageLoad(image){
// document.body.appendChild(image.image);
// alert("image loaded and the size is " + image.width + "*" + image.height);
//}
//img.load();
function EnhancedImage(src,onLoaded){
var self = this;
this.src = src;
this.width = 0;
this.height = 0;
this.onLoaded = onLoaded;
this.loaded = false;
this.image = null;
this.load = function(){
if(this.loaded)
return;
this.image = new Image();
this.image.src = this.src;
function loadImage(){
if(self.width != 0 && self.height != 0){
clearInterval(interval);
self.loaded = true;
self.onLoaded(self);//將實例傳入回調函數
}
self.width = self.image.width;//是number類型
self.height = self.image.height;
}
var interval = setInterval(loadImage,100);
}
}
/**
* 時間對象的格式化; 格式爲yyyy-MM-dd hh:mm:ss
*/
Date.prototype.format = function(format){
if(!format|| format == ""){
format = "yyyy年MM月dd";
}
var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(), //day
"h+" : this.getHours(), //hour
"m+" : this.getMinutes(), //minute
"s+" : this.getSeconds(), //second
"q+" : Math.floor((this.getMonth()+3)/3), //quarter
"S" : this.getMilliseconds() //millisecond
}
if(/(y+)/.test(format))format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
for(var k in o)if(new RegExp("("+ k +")").test(format))
format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] :("00"+ o[k]).substr((""+ o[k]).length));
return format;
}
/**
* 時間對象的格式化;
* @dateTime {string} 要格式化的日期字符串
* @format {string} 格式化字符 可爲空
*/
function formatDateTime(temper,format){
var myDate = new Date(temper.replace(/[-]/g,'/'));
return myDate.format(format);//格式化時間
}
/**
* 將字符串轉換爲js日期格式(new Date);
* @dateTime {string} 要格式化的日期字符串
*/
function GetDateObj(temper){
var myDate = new Date(temper.replace(/[-]/g,'/'));
return myDate;
}
Date.prototype.addDay=function(num){
this.setDate(this.getDate()+num);
return this;
}
Date.prototype.addMonth=function(num){
var tempDate=this.getDate();
this.setMonth(this.getMonth()+num);
if(tempDate!=this.getDate()) this.setDate(0);
return this;
}
Date.prototype.addYear=function(num){
var tempDate=this.getDate();
this.setYear(this.getYear()+num);
if(tempDate!=this.getDate()) this.setDate(0);
return this;
}
Date.prototype.add = function(part,num){
var datecopy;
var ms = this.getTime();
num = parseInt(num);
switch(part){
case "ms":
ms += num;
break;
case "ss":
ms += 1000 * num;
break;
case "mi":
ms += 60 * 1000 * num;
break;
case "hh":
ms += 60 * 60 * 1000 * num;
break;
case "dd":
ms += 24 * 60 * 60 * 1000 * num;
break;
case "wk":
ms += 7 * 24 * 60 * 60 * 1000 * num;
break;
case "mm":
datecopy = new Date(Date.parse(this));
datecopy.setFullYear(this.getFullYear() + Math.floor((this.getMonth() + num) / 12));
var mth = (this.getMonth() + num) % 12;
if(mth < 0)mth += 12;
datecopy.setMonth(mth);
break;
case "qq":
datecopy = new Date(Date.parse(this));
datecopy.setFullYear(this.getFullYear() + Math.floor((this.getMonth() + 3 * num) / 12));
var mth = (this.getMonth() + 3 * num) % 12;
if(mth < 0)mth += 12;
datecopy.setMonth(mth);
break;
case "yy":
datecopy = new Date(Date.parse(this));
datecopy.setFullYear(this.getFullYear() + num);
break;
}
if(datecopy == null)
return new Date(ms);
else
return datecopy;
}
/*
* (c)2006 Jesse Skinner/Dean Edwards/Matthias Miller/John Resig
* Special thanks to Dan Webb's domready.js Prototype extension
* and Simon Willison's addLoadEvent
*
* For more info, see:
* http://www.thefutureoftheweb.com/blog/adddomloadevent
* http://dean.edwards.name/weblog/2006/06/again/
* http://www.vivabit.com/bollocks/2006/06/21/a-dom-ready-extension-for-prototype
* http://simon.incutio.com/archive/2004/05/26/addLoadEvent
*
*
* To use: call addDOMLoadEvent one or more times with functions, ie:
*
* function something() {
* // do something
* }
* addDOMLoadEvent(something);
*
* addDOMLoadEvent(function() {
* // do other stuff
* });
*
*/
addDOMLoadEvent = (function(){
// create event function stack
var load_events = [],
load_timer,
script,
done,
exec,
old_onload,
init = function () {
done = true;
// kill the timer
clearInterval(load_timer);
// execute each function in the stack in the order they were added
while (exec = load_events.shift())
exec();
if (script) script.onreadystatechange = '';
};
return function (func) {
// if the init function was already ran, just run this function now and stop
if (done) return func();
if (!load_events[0]) {
// for Mozilla/Opera9
if (document.addEventListener)
document.addEventListener("DOMContentLoaded", init, false);
// for Internet Explorer
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>");
script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete")
init(); // call the onload handler
};
/*@end @*/
// for Safari
if (/WebKit/i.test(navigator.userAgent)) { // sniff
load_timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState))
init(); // call the onload handler
}, 10);
}
// for other browsers set the window.onload, but also execute the old window.onload
old_onload = window.onload;
window.onload = function() {
init();
if (old_onload) old_onload();
};
}
load_events.push(func);
}
})();
/**
* 截取字符串 區別漢字和英文
* @name {string} 要截取的字符串
* @maxLength {int} 截取長度 可爲空 默認20
*/
function widthCheck(name, maxLength){
if(name==null||name==""){
return "";
}
if(!maxLength){
maxLength = 20;
}
if(name==null||name.length<1){
return ["", ""];
}
var w = 0;//字符串長度,一個漢字長度爲2
var s = 0;//漢字個數
var p = false;//判斷字符串當前循環的前一個字符是否爲漢字
var b = false;//判斷字符串當前循環的字符是否爲漢字
var nameSub;
for (var i=0; i<name.length; i++) {
if(i>1 && b==false){
p = false;
}
if(i>1 && b==true){
p = true;
}
var c = name.charCodeAt(i);
//單字節加1
if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
w++;
b = false;
}else {
w+=2;
s++;
b = true;
}
if(w>maxLength && i<=name.length-1){
if(b==true && p==true){
nameSub = name.substring(0,i-2)+"...";
}
if(b==false && p==false){
nameSub = name.substring(0,i-3)+"...";
}
if(b==true && p==false){
nameSub = name.substring(0,i-2)+"...";
}
if(p==true){
nameSub = name.substring(0,i-2)+"...";
}
break;
}
}
if(w<=maxLength){
return name;
}
return nameSub;
}
/**
* json對象轉換爲字符串
* @obj {obj} json對象
*/
function jsonToString(obj){
var THIS = this;
switch(typeof(obj)){
case 'string':
return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
case 'array':
return '[' + obj.map(THIS.jsonToString).join(',') + ']';
case 'object':
if(obj instanceof Array){
var strArr = [];
var len = obj.length;
for(var i=0; i<len; i++){
strArr.push(THIS.jsonToString(obj[i]));
}
return '[' + strArr.join(',') + ']';
}else if(obj==null){
return 'null';
}else{
var string = [];
for (var property in obj) string.push(THIS.jsonToString(property) + ':' + THIS.jsonToString(obj[property]));
return '{' + string.join(',') + '}';
}
case 'number':
return obj;
case false:
return obj;
}
}
/*
* 方法:Array.remove(dx)
* 功能:刪除數組元素.
* 參數:dx刪除元素的下標.
* 返回:在原數組上修改數組
*/
Array.prototype.remove=function(dx){
if(isNaN(dx)||dx>this.length){return false;}
for(var i=0,n=0;i<this.length;i++){
if(this[i]!=this[dx]){
this[n++]=this[i]
}
}
this.length-=1
}
/**
* 字符串轉換爲json對象
* @obj {string} json字符串
*/
function stringToJSON(obj){
return eval('(' + obj + ')');
}
//獲取鼠標座標
//var mousePos = new mouseCoords(window.event);
function mouseCoords(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX + document.documentElement.scrollLeft - document.documentElement.clientLeft,
y:ev.clientY + document.documentElement.scrollTop - document.documentElement.clientTop
};
}
function CPos(x, y){
this.x = x;
this.y = y;
}
/**
* 得到對象的相對瀏覽器的座標
* var obj = document.getElementById('divid')
* alert(GetObjPos(obj)['x']) //x座標
* alert(GetObjPos(obj)['y']) //y座標
*/
function GetObjPos(ATarget){
var target = ATarget;
var pos = new CPos(target.offsetLeft, target.offsetTop);
var target = target.offsetParent;
while (target){
pos.x += target.offsetLeft;
pos.y += target.offsetTop;
target = target.offsetParent
}
return pos;
}
//禁止嵌套事件穿透 將該方法用到事件方法內即可
function CancelBubble(){
if (event.stopPropagation){
event.stopPropagation();//在基於firefox內核的瀏覽器中支持做法stopPropagation
}else{
event.cancelBubble = true;//基於ie的寫法
}
}
/**
* 添加事件到對象
* obj: html對象
* type:事件名稱 例如click(去除前面on)
* fn: 函數對象
* args:參數
*/
function addEventListener(obj,type,fn,args){
var eventHandler = fn;
if(args){
eventHander = function(e){
fn.call(args, e);
}
}
if (obj.attachEvent){
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
obj.attachEvent('on'+type, obj[type+fn]);
} else
obj.addEventListener(type,fn,false);
}
/**
* 移除事件
* obj: html對象
* type:事件名稱 例如click(去除前面on)
* fn: 函數對象
*/
function removeEventListener(obj,type,fn) {
if(obj.detachEvent){
obj.detachEvent('on'+type,obj[type+fn]);
obj[type+fn] = null;
}else
obj.removeEventListener( type, fn, false );
}
//將字符轉換成10進制整型
function parseInt10(n){return parseInt(n, 10);}
//獲取禮拜幾根據指定日期
function GetWeekName(_dateTime){
var day=[ "日", "一", "二", "三", "四", "五", "六"];
return "星期"+day[_dateTime.getDay()];
}
常用js方法收集
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.