/**
* @file transport.js
* @description 用于支持ajax的传输类。
* @author ecshop r&d team ( http://www.ecshop.com/ )
* @date 2007-03-08 wednesday
* @license licensed under the academic free license 2.1 http://www.opensource.org/licenses/afl-2.1.php
* @version 1.0.20070308
**/
var transport =
{
/* *
* 存储本对象所在的文件名。
*
* @static
*/
filename : "transport.js",
/* *
* 存储是否进入调试模式的开关,打印调试消息的方式,换行符,调试用的容器的id。
*
* @private
*/
debugging :
{
isdebugging : 0,
debuggingmode : 0,
linefeed : "",
containerid : 0
},
/* *
* 设置调试模式以及打印调试消息方式的方法。
*
* @public
* @param {int} 是否打开调试模式 0:关闭,1:打开
* @param {int} 打印调试消息的方式 0:alert,1:innerhtml
*
*/
debug : function (isdebugging, debuggingmode)
{
this.debugging =
{
"isdebugging" : isdebugging,
"debuggingmode" : debuggingmode,
"linefeed" : debuggingmode ? "
" : "\n",
"containerid" : "dubugging-container" + new date().gettime()
};
},
/* *
* 传输完毕后自动调用的方法,优先级比用户从run()方法中传入的回调函数高。
*
* @public
*/
oncomplete : function ()
{
},
/* *
* 传输过程中自动调用的方法。
*
* @public
*/
onrunning : function ()
{
},
/* *
* 调用此方法发送http请求。
*
* @public
* @param {string} url 请求的url地址
* @param {mix} params 发送参数
* @param {function} callback 回调函数
* @param {string} ransfermode 请求的方式,有"get"和"post"两种
* @param {string} responsetype 响应类型,有"json"、"xml"和"text"三种
* @param {boolean} asyn 是否异步请求的方式
* @param {boolean} quiet 是否安静模式请求
*/
run : function (url, params, callback, transfermode, responsetype, asyn, quiet)
{
/* 处理用户在调用该方法时输入的参数 */
params = this.parseparams(params);
transfermode = typeof(transfermode) === "string"
&& transfermode.touppercase() === "get"
? "get"
: "post";
if (transfermode === "get")
{
var d = new date();
url += params ? (url.indexof("?") === - 1 ? "?" : "&") + params : "";
url = encodeuri(url) + (url.indexof("?") === - 1 ? "?" : "&") + d.gettime() + d.getmilliseconds();
params = null;
}
responsetype = typeof(responsetype) === "string" && ((responsetype = responsetype.touppercase()) === "json" || responsetype === "xml") ? responsetype : "text";
asyn = asyn === false ? false : true;
/* 处理http请求和响应 */
var xhr = this.createxmlhttprequest();
try
{
var self = this;
if (typeof(self.onrunning) === "function" && !quiet)
{
self.onrunning();
}
xhr.open(transfermode, url, asyn);
if (transfermode === "post")
{
xhr.setrequestheader("content-type", "application/x-www-form-urlencoded");
}
if (asyn)
{
xhr.onreadystatechange = function ()
{
if (xhr.readystate == 4)
{
switch ( xhr.status )
{
case 0:
case 200: // ok!
/*
* if the request was to create a new resource
* (such as post an item to the database)
* you could instead return a status code of '201 created'
*/
if (typeof(self.oncomplete) === "function")
{
self.oncomplete();
}
if (typeof(callback) === "function")
{
callback.call(self, self.parseresult(responsetype, xhr), xhr.responsetext);
}
break;
case 304: // not modified
/*
* this would be used when your ajax widget is
* checking for updated content,
* such as the twitter interface.
*/
break;
case 400: // bad request
/*
* a bit like a safety net for requests by your js interface
* that aren't supported on the server.
* "your browser made a request that the server cannot understand"
*/
alert("xmlhttprequest status: [400] bad request");
break;
case 404: // not found
alert("xmlhttprequest status: [404] \nthe requested url "+url+" was not found on this server.");
break;
case 409: // conflict
/*
* perhaps your javascript request attempted to
* update a database record
* but failed due to a conflict
* (eg: a field that must be unique)
*/
break;
case 503: // service unavailable
/*
* a resource that this request relies upon
* is currently unavailable
* (eg: a file is locked by another process)
*/
alert("xmlhttprequest status: [503] service unavailable");
break;
default:
alert("xmlhttprequest status: [" + xhr.status + "] unknow status.");
}
xhr = null;
}
}
if (xhr != null) xhr.send(params);
}
else
{
if (typeof(self.onrunning) === "function")
{
self.onrunning();
}
xhr.send(params);
var result = self.parseresult(responsetype, xhr);
//xhr = null;
if (typeof(self.oncomplete) === "function")
{
self.oncomplete();
}
if (typeof(callback) === "function")
{
callback.call(self, result, xhr.responsetext);
}
return result;
}
}
catch (ex)
{
if (typeof(self.oncomplete) === "function")
{
self.oncomplete();
}
alert(this.filename + "/run() error:" + ex.description);
}
},
/* *
* 如果开启了调试模式,该方法会打印出相应的信息。
*
* @private
* @param {string} info 调试信息
* @param {string} type 信息类型
*/
displaydebugginginfo : function (info, type)
{
if ( ! this.debugging.debuggingmode)
{
alert(info);
}
else
{
var id = this.debugging.containerid;
if ( ! document.getelementbyid(id))
{
div = document.createelement("div");
div.id = id;
div.style.position = "absolute";
div.style.width = "98%";
div.style.border = "1px solid #f00";
div.style.backgroundcolor = "#eef";
var pageyoffset = document.body.scrolltop
|| window.pageyoffset
|| 0;
div.style.top = document.body.clientheight * 0.6
+ pageyoffset
+ "px";
document.body.appendchild(div);
div.innerhtml = "
"
+ "
"
+ "";
}
var subdivs = div.getelementsbytagname("div");
if (type === "param")
{
subdivs[0].innerhtml = info;
}
else
{
subdivs[1].innerhtml = info;
}
}
},
/* *
* 创建xmlhttprequest对象的方法。
*
* @private
* @return 返回一个xmlhttprequest对象
* @type object
*/
createxmlhttprequest : function ()
{
var xhr = null;
if (window.activexobject)
{
var versions = ['microsoft.xmlhttp', 'msxml6.xmlhttp', 'msxml5.xmlhttp', 'msxml4.xmlhttp', 'msxml3.xmlhttp', 'msxml2.xmlhttp', 'msxml.xmlhttp'];
for (var i = 0; i < versions.length; i ++ )
{
try
{
xhr = new activexobject(versions[i]);
break;
}
catch (ex)
{
continue;
}
}
}
else
{
xhr = new xmlhttprequest();
}
return xhr;
},
/* *
* 当传输过程发生错误时将调用此方法。
*
* @private
* @param {object} xhr xmlhttprequest对象
* @param {string} url http请求的地址
*/
onxmlhttprequesterror : function (xhr, url)
{
throw "url: " + url + "\n"
+ "readystate: " + xhr.readystate + "\n"
+ "state: " + xhr.status + "\n"
+ "headers: " + xhr.getallresponseheaders();
},
/* *
* 对将要发送的参数进行格式化。
*
* @private
* @params {mix} params 将要发送的参数
* @return 返回合法的参数
* @type string
*/
parseparams : function (params)
{
var legalparams = "";
params = params ? params : "";
if (typeof(params) === "string")
{
legalparams = params;
}
else if (typeof(params) === "object")
{
try
{
legalparams = "json=" + $.tojson(params);
}
catch (ex)
{
alert("can't stringify json!");
return false;
}
}
else
{
alert("invalid parameters!");
return false;
}
if (this.debugging.isdebugging)
{
var lf = this.debugging.linefeed,
info = "[original parameters]" + lf + params + lf + lf
+ "[parsed parameters]" + lf + legalparams;
this.displaydebugginginfo(info, "param");
}
return legalparams;
},
/* *
* 对返回的http响应结果进行过滤。
*
* @public
* @params {mix} result http响应结果
* @return 返回过滤后的结果
* @type string
*/
prefilter : function (result)
{
return result.replace(/\xef\xbb\xbf/g, "");
},
/* *
* 对返回的结果进行格式化。
*
* @private
* @return 返回特定格式的数据结果
* @type mix
*/
parseresult : function (responsetype, xhr)
{
var result = null;
switch (responsetype)
{
case "json" :
result = this.prefilter(xhr.responsetext);
try
{
result = $.evaljson(result);
}
catch (ex)
{
throw this.filename + "/parseresult() error: can't parse to json.\n\n" + xhr.responsetext;
}
break;
case "xml" :
result = xhr.responsexml;
break;
case "text" :
result = this.prefilter(xhr.responsetext);
break;
default :
throw this.filename + "/parseresult() error: unknown response type:" + responsetype;
}
if (this.debugging.isdebugging)
{
var lf = this.debugging.linefeed,
info = "[response result of " + responsetype + " format]" + lf
+ result;
if (responsetype === "json")
{
info = "[response result of text format]" + lf
+ xhr.responsetext + lf + lf
+ info;
}
this.displaydebugginginfo(info, "result");
}
return result;
}
};
/* 定义两个别名 */
var ajax = transport;
ajax.call = transport.run;
/*
json.js
2007-03-06
public domain
this file adds these methods to javascript:
array.tojsonstring()
boolean.tojsonstring()
date.tojsonstring()
number.tojsonstring()
object.tojsonstring()
string.tojsonstring()
these methods produce a json text from a javascript value.
it must not contain any cyclical references. illegal values
will be excluded.
the default conversion for dates is to an iso string. you can
add a tojsonstring method to any date object to get a different
representation.
string.parsejson(filter)
this method parses a json text to produce an object or
array. it can throw a syntaxerror exception.
the optional filter parameter is a function which can filter and
transform the results. it receives each of the keys and values, and
its return value is used instead of the original value. if it
returns what it received, then structure is not modified. if it
returns undefined then the member is deleted.
example:
// parse the text. if a key contains the string 'date' then
// convert the value to a date.
mydata = text.parsejson(function (key, value) {
return key.indexof('date') >= 0 ? new date(value) : value;
});
it is expected that these methods will formally become part of the
javascript programming language in the fourth edition of the
ecmascript standard in 2008.
*/
// augment the basic prototypes if they have not already been augmented.
/*
if ( ! object.prototype.tojsonstring) {
array.prototype.tojsonstring = function () {
var a = ['['], // the array holding the text fragments.
b, // a boolean indicating that a comma is required.
i, // loop counter.
l = this.length,
v; // the value to be stringified.
function p(s) {
// p accumulates text fragments in an array. it inserts a comma before all
// except the first fragment.
if (b) {
a.push(',');
}
a.push(s);
b = true;
}
// for each value in this array...
for (i = 0; i < l; i ++) {
v = this[i];
switch (typeof v) {
// values without a json representation are ignored.
case 'undefined':
case 'function':
case 'unknown':
break;
// serialize a javascript object value. ignore objects thats lack the
// tojsonstring method. due to a specification error in ecmascript,
// typeof null is 'object', so watch out for that case.
case 'object':
if (v) {
if (typeof v.tojsonstring === 'function') {
p(v.tojsonstring());
}
} else {
p("null");
}
break;
// otherwise, serialize the value.
default:
p(v.tojsonstring());
}
}
// join all of the fragments together and return.
a.push(']');
return a.join('');
};
boolean.prototype.tojsonstring = function () {
return string(this);
};
date.prototype.tojsonstring = function () {
// ultimately, this method will be equivalent to the date.toisostring method.
function f(n) {
// format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return '"' + this.getfullyear() + '-' +
f(this.getmonth() + 1) + '-' +
f(this.getdate()) + 't' +
f(this.gethours()) + ':' +
f(this.getminutes()) + ':' +
f(this.getseconds()) + '"';
};
number.prototype.tojsonstring = function () {
// json numbers must be finite. encode non-finite numbers as null.
return isfinite(this) ? string(this) : "null";
};
object.prototype.tojsonstring = function () {
var a = ['{'], // the array holding the text fragments.
b, // a boolean indicating that a comma is required.
k, // the current key.
v; // the current value.
function p(s) {
// p accumulates text fragment pairs in an array. it inserts a comma before all
// except the first fragment pair.
if (b) {
a.push(',');
}
a.push(k.tojsonstring(), ':', s);
b = true;
}
// iterate through all of the keys in the object, ignoring the proto chain.
for (k in this) {
if (this.hasownproperty(k)) {
v = this[k];
switch (typeof v) {
// values without a json representation are ignored.
case 'undefined':
case 'function':
case 'unknown':
break;
// serialize a javascript object value. ignore objects that lack the
// tojsonstring method. due to a specification error in ecmascript,
// typeof null is 'object', so watch out for that case.
case 'object':
if (this !== window)
{
if (v) {
if (typeof v.tojsonstring === 'function') {
p(v.tojsonstring());
}
} else {
p("null");
}
}
break;
default:
p(v.tojsonstring());
}
}
}
// join all of the fragments together and return.
a.push('}');
return a.join('');
};
(function (s) {
// augment string.prototype. we do this in an immediate anonymous function to
// avoid defining global variables.
// m is a table of character substitutions.
var m = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
s.parsejson = function (filter) {
// parsing happens in three stages. in the first stage, we run the text against
// a regular expression which looks for non-json characters. we are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. but just to be safe, we will reject all
// unexpected characters.
try {
if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+eaeflnr-u \n\r\t])+?$/.
test(this)) {
// in the second stage we use the eval function to compile the text into a
// javascript structure. the '{' operator is subject to a syntactic ambiguity
// in javascript: it can begin a block or an object literal. we wrap the text
// in parens to eliminate the ambiguity.
var j = eval('(' + this + ')');
// in the optional third stage, we recursively walk the new structure, passing
// each name/value pair to a filter function for possible transformation.
if (typeof filter === 'function') {
function walk(k, v) {
if (v && typeof v === 'object') {
for (var i in v) {
if (v.hasownproperty(i)) {
v[i] = walk(i, v[i]);
}
}
}
return filter(k, v);
}
j = walk('', j);
}
return j;
}
} catch (e) {
// fall through if the regexp test fails.
}
throw new syntaxerror("parsejson");
};
s.tojsonstring = function () {
// if the string contains no control characters, no quote characters, and no
// backslash characters, then we can simply slap some quotes around it.
// otherwise we must also replace the offending characters with safe
// sequences.
// add by weberliu @ 2007-4-2
var _self = this.replace("&", "%26");
if (/["\\\x00-\x1f]/.test(this)) {
return '"' + _self.replace(/([\x00-\x1f\\"])/g, function(a, b) {
var c = m[b];
if (c) {
return c;
}
c = b.charcodeat();
return '\\u00' +
math.floor(c / 16).tostring(16) +
(c % 16).tostring(16);
}) + '"';
}
return '"' + _self + '"';
};
})(string.prototype);
}
*/
ajax.onrunning = showloader;
ajax.oncomplete = hideloader;
/* *
* 显示载入信息
*/
function showloader()
{
document.getelementsbytagname('body').item(0).style.cursor = "wait";
if (top.frames['header-frame'] && top.frames['header-frame'].document.getelementbyid("load-div"))
{
top.frames['header-frame'].document.getelementbyid("load-div").style.display = "block";
}
else
{
var obj = document.getelementbyid('loader');
if ( ! obj && typeof(process_request) != 'undefined')
{
obj = document.createelement("div");
obj.id = "loader";
obj.innerhtml = process_request;
document.body.appendchild(obj);
}
}
}
/* *
* 隐藏载入信息
*/
function hideloader()
{
document.getelementsbytagname('body').item(0).style.cursor = "auto";
if (top.frames['header-frame'] && top.frames['header-frame'].document.getelementbyid("load-div"))
{
settimeout(function(){top.frames['header-frame'].document.getelementbyid("load-div").style.display = "none"}, 10);
}
else
{
try
{
var obj = document.getelementbyid("loader");
obj.style.display = 'none';
document.body.removechild(obj);
}
catch (ex)
{}
}
}