transport.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. /**
  2. * @file transport.js
  3. * @description 用于支持AJAX的传输类。
  4. * @author ECShop R&D Team ( http://www.ecshop.com/ )
  5. * @date 2007-03-08 Wednesday
  6. * @license Licensed under the Academic Free License 2.1 http://www.opensource.org/licenses/afl-2.1.php
  7. * @version 1.0.20070308
  8. **/
  9. var Transport =
  10. {
  11. /* *
  12. * 存储本对象所在的文件名。
  13. *
  14. * @static
  15. */
  16. filename : "transport.js",
  17. /* *
  18. * 存储是否进入调试模式的开关,打印调试消息的方式,换行符,调试用的容器的ID。
  19. *
  20. * @private
  21. */
  22. debugging :
  23. {
  24. isDebugging : 0,
  25. debuggingMode : 0,
  26. linefeed : "",
  27. containerId : 0
  28. },
  29. /* *
  30. * 设置调试模式以及打印调试消息方式的方法。
  31. *
  32. * @public
  33. * @param {int} 是否打开调试模式 0:关闭,1:打开
  34. * @param {int} 打印调试消息的方式 0:alert,1:innerHTML
  35. *
  36. */
  37. debug : function (isDebugging, debuggingMode)
  38. {
  39. this.debugging =
  40. {
  41. "isDebugging" : isDebugging,
  42. "debuggingMode" : debuggingMode,
  43. "linefeed" : debuggingMode ? "<br />" : "\n",
  44. "containerId" : "dubugging-container" + new Date().getTime()
  45. };
  46. },
  47. /* *
  48. * 传输完毕后自动调用的方法,优先级比用户从run()方法中传入的回调函数高。
  49. *
  50. * @public
  51. */
  52. onComplete : function ()
  53. {
  54. },
  55. /* *
  56. * 传输过程中自动调用的方法。
  57. *
  58. * @public
  59. */
  60. onRunning : function ()
  61. {
  62. },
  63. /* *
  64. * 调用此方法发送HTTP请求。
  65. *
  66. * @public
  67. * @param {string} url 请求的URL地址
  68. * @param {mix} params 发送参数
  69. * @param {Function} callback 回调函数
  70. * @param {string} ransferMode 请求的方式,有"GET"和"POST"两种
  71. * @param {string} responseType 响应类型,有"JSON"、"XML"和"TEXT"三种
  72. * @param {boolean} asyn 是否异步请求的方式
  73. * @param {boolean} quiet 是否安静模式请求
  74. */
  75. run : function (url, params, callback, transferMode, responseType, asyn, quiet)
  76. {
  77. /* 处理用户在调用该方法时输入的参数 */
  78. params = this.parseParams(params);
  79. transferMode = typeof(transferMode) === "string"
  80. && transferMode.toUpperCase() === "GET"
  81. ? "GET"
  82. : "POST";
  83. if (transferMode === "GET")
  84. {
  85. var d = new Date();
  86. url += params ? (url.indexOf("?") === - 1 ? "?" : "&") + params : "";
  87. url = encodeURI(url) + (url.indexOf("?") === - 1 ? "?" : "&") + d.getTime() + d.getMilliseconds();
  88. params = null;
  89. }
  90. responseType = typeof(responseType) === "string" && ((responseType = responseType.toUpperCase()) === "JSON" || responseType === "XML") ? responseType : "TEXT";
  91. asyn = asyn === false ? false : true;
  92. /* 处理HTTP请求和响应 */
  93. var xhr = this.createXMLHttpRequest();
  94. try
  95. {
  96. var self = this;
  97. if (typeof(self.onRunning) === "function" && !quiet)
  98. {
  99. self.onRunning();
  100. }
  101. xhr.open(transferMode, url, asyn);
  102. if (transferMode === "POST")
  103. {
  104. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  105. }
  106. if (asyn)
  107. {
  108. xhr.onreadystatechange = function ()
  109. {
  110. if (xhr.readyState == 4)
  111. {
  112. switch ( xhr.status )
  113. {
  114. case 0:
  115. case 200: // OK!
  116. /*
  117. * If the request was to create a new resource
  118. * (such as post an item to the database)
  119. * You could instead return a status code of '201 Created'
  120. */
  121. if (typeof(self.onComplete) === "function")
  122. {
  123. self.onComplete();
  124. }
  125. if (typeof(callback) === "function")
  126. {
  127. callback.call(self, self.parseResult(responseType, xhr), xhr.responseText);
  128. }
  129. break;
  130. case 304: // Not Modified
  131. /*
  132. * This would be used when your Ajax widget is
  133. * checking for updated content,
  134. * such as the Twitter interface.
  135. */
  136. break;
  137. case 400: // Bad Request
  138. /*
  139. * A bit like a safety net for requests by your JS interface
  140. * that aren't supported on the server.
  141. * "Your browser made a request that the server cannot understand"
  142. */
  143. alert("XmlHttpRequest status: [400] Bad Request");
  144. break;
  145. case 404: // Not Found
  146. alert("XmlHttpRequest status: [404] \nThe requested URL "+url+" was not found on this server.");
  147. break;
  148. case 409: // Conflict
  149. /*
  150. * Perhaps your JavaScript request attempted to
  151. * update a Database record
  152. * but failed due to a conflict
  153. * (eg: a field that must be unique)
  154. */
  155. break;
  156. case 503: // Service Unavailable
  157. /*
  158. * A resource that this request relies upon
  159. * is currently unavailable
  160. * (eg: a file is locked by another process)
  161. */
  162. alert("XmlHttpRequest status: [503] Service Unavailable");
  163. break;
  164. default:
  165. alert("XmlHttpRequest status: [" + xhr.status + "] Unknow status.");
  166. }
  167. xhr = null;
  168. }
  169. }
  170. if (xhr != null) xhr.send(params);
  171. }
  172. else
  173. {
  174. if (typeof(self.onRunning) === "function")
  175. {
  176. self.onRunning();
  177. }
  178. xhr.send(params);
  179. var result = self.parseResult(responseType, xhr);
  180. //xhr = null;
  181. if (typeof(self.onComplete) === "function")
  182. {
  183. self.onComplete();
  184. }
  185. if (typeof(callback) === "function")
  186. {
  187. callback.call(self, result, xhr.responseText);
  188. }
  189. return result;
  190. }
  191. }
  192. catch (ex)
  193. {
  194. if (typeof(self.onComplete) === "function")
  195. {
  196. self.onComplete();
  197. }
  198. alert(this.filename + "/run() error:" + ex.description);
  199. }
  200. },
  201. /* *
  202. * 如果开启了调试模式,该方法会打印出相应的信息。
  203. *
  204. * @private
  205. * @param {string} info 调试信息
  206. * @param {string} type 信息类型
  207. */
  208. displayDebuggingInfo : function (info, type)
  209. {
  210. if ( ! this.debugging.debuggingMode)
  211. {
  212. alert(info);
  213. }
  214. else
  215. {
  216. var id = this.debugging.containerId;
  217. if ( ! document.getElementById(id))
  218. {
  219. div = document.createElement("DIV");
  220. div.id = id;
  221. div.style.position = "absolute";
  222. div.style.width = "98%";
  223. div.style.border = "1px solid #f00";
  224. div.style.backgroundColor = "#eef";
  225. var pageYOffset = document.body.scrollTop
  226. || window.pageYOffset
  227. || 0;
  228. div.style.top = document.body.clientHeight * 0.6
  229. + pageYOffset
  230. + "px";
  231. document.body.appendChild(div);
  232. div.innerHTML = "<div></div>"
  233. + "<hr style='height:1px;border:1px dashed red;'>"
  234. + "<div></div>";
  235. }
  236. var subDivs = div.getElementsByTagName("DIV");
  237. if (type === "param")
  238. {
  239. subDivs[0].innerHTML = info;
  240. }
  241. else
  242. {
  243. subDivs[1].innerHTML = info;
  244. }
  245. }
  246. },
  247. /* *
  248. * 创建XMLHttpRequest对象的方法。
  249. *
  250. * @private
  251. * @return 返回一个XMLHttpRequest对象
  252. * @type Object
  253. */
  254. createXMLHttpRequest : function ()
  255. {
  256. var xhr = null;
  257. if (window.ActiveXObject)
  258. {
  259. var versions = ['Microsoft.XMLHTTP', 'MSXML6.XMLHTTP', 'MSXML5.XMLHTTP', 'MSXML4.XMLHTTP', 'MSXML3.XMLHTTP', 'MSXML2.XMLHTTP', 'MSXML.XMLHTTP'];
  260. for (var i = 0; i < versions.length; i ++ )
  261. {
  262. try
  263. {
  264. xhr = new ActiveXObject(versions[i]);
  265. break;
  266. }
  267. catch (ex)
  268. {
  269. continue;
  270. }
  271. }
  272. }
  273. else
  274. {
  275. xhr = new XMLHttpRequest();
  276. }
  277. return xhr;
  278. },
  279. /* *
  280. * 当传输过程发生错误时将调用此方法。
  281. *
  282. * @private
  283. * @param {Object} xhr XMLHttpRequest对象
  284. * @param {String} url HTTP请求的地址
  285. */
  286. onXMLHttpRequestError : function (xhr, url)
  287. {
  288. throw "URL: " + url + "\n"
  289. + "readyState: " + xhr.readyState + "\n"
  290. + "state: " + xhr.status + "\n"
  291. + "headers: " + xhr.getAllResponseHeaders();
  292. },
  293. /* *
  294. * 对将要发送的参数进行格式化。
  295. *
  296. * @private
  297. * @params {mix} params 将要发送的参数
  298. * @return 返回合法的参数
  299. * @type string
  300. */
  301. parseParams : function (params)
  302. {
  303. var legalParams = "";
  304. params = params ? params : "";
  305. if (typeof(params) === "string")
  306. {
  307. legalParams = params;
  308. }
  309. else if (typeof(params) === "object")
  310. {
  311. try
  312. {
  313. legalParams = "JSON=" + $.toJSON(params);
  314. }
  315. catch (ex)
  316. {
  317. alert("Can't stringify JSON!");
  318. return false;
  319. }
  320. }
  321. else
  322. {
  323. alert("Invalid parameters!");
  324. return false;
  325. }
  326. if (this.debugging.isDebugging)
  327. {
  328. var lf = this.debugging.linefeed,
  329. info = "[Original Parameters]" + lf + params + lf + lf
  330. + "[Parsed Parameters]" + lf + legalParams;
  331. this.displayDebuggingInfo(info, "param");
  332. }
  333. return legalParams;
  334. },
  335. /* *
  336. * 对返回的HTTP响应结果进行过滤。
  337. *
  338. * @public
  339. * @params {mix} result HTTP响应结果
  340. * @return 返回过滤后的结果
  341. * @type string
  342. */
  343. preFilter : function (result)
  344. {
  345. return result.replace(/\xEF\xBB\xBF/g, "");
  346. },
  347. /* *
  348. * 对返回的结果进行格式化。
  349. *
  350. * @private
  351. * @return 返回特定格式的数据结果
  352. * @type mix
  353. */
  354. parseResult : function (responseType, xhr)
  355. {
  356. var result = null;
  357. switch (responseType)
  358. {
  359. case "JSON" :
  360. result = this.preFilter(xhr.responseText);
  361. try
  362. {
  363. result = $.evalJSON(result);
  364. }
  365. catch (ex)
  366. {
  367. throw this.filename + "/parseResult() error: can't parse to JSON.\n\n" + xhr.responseText;
  368. }
  369. break;
  370. case "XML" :
  371. result = xhr.responseXML;
  372. break;
  373. case "TEXT" :
  374. result = this.preFilter(xhr.responseText);
  375. break;
  376. default :
  377. throw this.filename + "/parseResult() error: unknown response type:" + responseType;
  378. }
  379. if (this.debugging.isDebugging)
  380. {
  381. var lf = this.debugging.linefeed,
  382. info = "[Response Result of " + responseType + " Format]" + lf
  383. + result;
  384. if (responseType === "JSON")
  385. {
  386. info = "[Response Result of TEXT Format]" + lf
  387. + xhr.responseText + lf + lf
  388. + info;
  389. }
  390. this.displayDebuggingInfo(info, "result");
  391. }
  392. return result;
  393. }
  394. };
  395. /* 定义两个别名 */
  396. var Ajax = Transport;
  397. Ajax.call = Transport.run;
  398. /*
  399. json.js
  400. 2007-03-06
  401. Public Domain
  402. This file adds these methods to JavaScript:
  403. array.toJSONString()
  404. boolean.toJSONString()
  405. date.toJSONString()
  406. number.toJSONString()
  407. object.toJSONString()
  408. string.toJSONString()
  409. These methods produce a JSON text from a JavaScript value.
  410. It must not contain any cyclical references. Illegal values
  411. will be excluded.
  412. The default conversion for dates is to an ISO string. You can
  413. add a toJSONString method to any date object to get a different
  414. representation.
  415. string.parseJSON(filter)
  416. This method parses a JSON text to produce an object or
  417. array. It can throw a SyntaxError exception.
  418. The optional filter parameter is a function which can filter and
  419. transform the results. It receives each of the keys and values, and
  420. its return value is used instead of the original value. If it
  421. returns what it received, then structure is not modified. If it
  422. returns undefined then the member is deleted.
  423. Example:
  424. // Parse the text. If a key contains the string 'date' then
  425. // convert the value to a date.
  426. myData = text.parseJSON(function (key, value) {
  427. return key.indexOf('date') >= 0 ? new Date(value) : value;
  428. });
  429. It is expected that these methods will formally become part of the
  430. JavaScript Programming Language in the Fourth Edition of the
  431. ECMAScript standard in 2008.
  432. */
  433. // Augment the basic prototypes if they have not already been augmented.
  434. /*
  435. if ( ! Object.prototype.toJSONString) {
  436. Array.prototype.toJSONString = function () {
  437. var a = ['['], // The array holding the text fragments.
  438. b, // A boolean indicating that a comma is required.
  439. i, // Loop counter.
  440. l = this.length,
  441. v; // The value to be stringified.
  442. function p(s) {
  443. // p accumulates text fragments in an array. It inserts a comma before all
  444. // except the first fragment.
  445. if (b) {
  446. a.push(',');
  447. }
  448. a.push(s);
  449. b = true;
  450. }
  451. // For each value in this array...
  452. for (i = 0; i < l; i ++) {
  453. v = this[i];
  454. switch (typeof v) {
  455. // Values without a JSON representation are ignored.
  456. case 'undefined':
  457. case 'function':
  458. case 'unknown':
  459. break;
  460. // Serialize a JavaScript object value. Ignore objects thats lack the
  461. // toJSONString method. Due to a specification error in ECMAScript,
  462. // typeof null is 'object', so watch out for that case.
  463. case 'object':
  464. if (v) {
  465. if (typeof v.toJSONString === 'function') {
  466. p(v.toJSONString());
  467. }
  468. } else {
  469. p("null");
  470. }
  471. break;
  472. // Otherwise, serialize the value.
  473. default:
  474. p(v.toJSONString());
  475. }
  476. }
  477. // Join all of the fragments together and return.
  478. a.push(']');
  479. return a.join('');
  480. };
  481. Boolean.prototype.toJSONString = function () {
  482. return String(this);
  483. };
  484. Date.prototype.toJSONString = function () {
  485. // Ultimately, this method will be equivalent to the date.toISOString method.
  486. function f(n) {
  487. // Format integers to have at least two digits.
  488. return n < 10 ? '0' + n : n;
  489. }
  490. return '"' + this.getFullYear() + '-' +
  491. f(this.getMonth() + 1) + '-' +
  492. f(this.getDate()) + 'T' +
  493. f(this.getHours()) + ':' +
  494. f(this.getMinutes()) + ':' +
  495. f(this.getSeconds()) + '"';
  496. };
  497. Number.prototype.toJSONString = function () {
  498. // JSON numbers must be finite. Encode non-finite numbers as null.
  499. return isFinite(this) ? String(this) : "null";
  500. };
  501. Object.prototype.toJSONString = function () {
  502. var a = ['{'], // The array holding the text fragments.
  503. b, // A boolean indicating that a comma is required.
  504. k, // The current key.
  505. v; // The current value.
  506. function p(s) {
  507. // p accumulates text fragment pairs in an array. It inserts a comma before all
  508. // except the first fragment pair.
  509. if (b) {
  510. a.push(',');
  511. }
  512. a.push(k.toJSONString(), ':', s);
  513. b = true;
  514. }
  515. // Iterate through all of the keys in the object, ignoring the proto chain.
  516. for (k in this) {
  517. if (this.hasOwnProperty(k)) {
  518. v = this[k];
  519. switch (typeof v) {
  520. // Values without a JSON representation are ignored.
  521. case 'undefined':
  522. case 'function':
  523. case 'unknown':
  524. break;
  525. // Serialize a JavaScript object value. Ignore objects that lack the
  526. // toJSONString method. Due to a specification error in ECMAScript,
  527. // typeof null is 'object', so watch out for that case.
  528. case 'object':
  529. if (this !== window)
  530. {
  531. if (v) {
  532. if (typeof v.toJSONString === 'function') {
  533. p(v.toJSONString());
  534. }
  535. } else {
  536. p("null");
  537. }
  538. }
  539. break;
  540. default:
  541. p(v.toJSONString());
  542. }
  543. }
  544. }
  545. // Join all of the fragments together and return.
  546. a.push('}');
  547. return a.join('');
  548. };
  549. (function (s) {
  550. // Augment String.prototype. We do this in an immediate anonymous function to
  551. // avoid defining global variables.
  552. // m is a table of character substitutions.
  553. var m = {
  554. '\b': '\\b',
  555. '\t': '\\t',
  556. '\n': '\\n',
  557. '\f': '\\f',
  558. '\r': '\\r',
  559. '"' : '\\"',
  560. '\\': '\\\\'
  561. };
  562. s.parseJSON = function (filter) {
  563. // Parsing happens in three stages. In the first stage, we run the text against
  564. // a regular expression which looks for non-JSON characters. We are especially
  565. // concerned with '()' and 'new' because they can cause invocation, and '='
  566. // because it can cause mutation. But just to be safe, we will reject all
  567. // unexpected characters.
  568. try {
  569. if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
  570. test(this)) {
  571. // In the second stage we use the eval function to compile the text into a
  572. // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
  573. // in JavaScript: it can begin a block or an object literal. We wrap the text
  574. // in parens to eliminate the ambiguity.
  575. var j = eval('(' + this + ')');
  576. // In the optional third stage, we recursively walk the new structure, passing
  577. // each name/value pair to a filter function for possible transformation.
  578. if (typeof filter === 'function') {
  579. function walk(k, v) {
  580. if (v && typeof v === 'object') {
  581. for (var i in v) {
  582. if (v.hasOwnProperty(i)) {
  583. v[i] = walk(i, v[i]);
  584. }
  585. }
  586. }
  587. return filter(k, v);
  588. }
  589. j = walk('', j);
  590. }
  591. return j;
  592. }
  593. } catch (e) {
  594. // Fall through if the regexp test fails.
  595. }
  596. throw new SyntaxError("parseJSON");
  597. };
  598. s.toJSONString = function () {
  599. // If the string contains no control characters, no quote characters, and no
  600. // backslash characters, then we can simply slap some quotes around it.
  601. // Otherwise we must also replace the offending characters with safe
  602. // sequences.
  603. // add by weberliu @ 2007-4-2
  604. var _self = this.replace("&", "%26");
  605. if (/["\\\x00-\x1f]/.test(this)) {
  606. return '"' + _self.replace(/([\x00-\x1f\\"])/g, function(a, b) {
  607. var c = m[b];
  608. if (c) {
  609. return c;
  610. }
  611. c = b.charCodeAt();
  612. return '\\u00' +
  613. Math.floor(c / 16).toString(16) +
  614. (c % 16).toString(16);
  615. }) + '"';
  616. }
  617. return '"' + _self + '"';
  618. };
  619. })(String.prototype);
  620. }
  621. */
  622. Ajax.onRunning = showLoader;
  623. Ajax.onComplete = hideLoader;
  624. /* *
  625. * 显示载入信息
  626. */
  627. function showLoader()
  628. {
  629. document.getElementsByTagName('body').item(0).style.cursor = "wait";
  630. if (top.frames['header-frame'] && top.frames['header-frame'].document.getElementById("load-div"))
  631. {
  632. top.frames['header-frame'].document.getElementById("load-div").style.display = "block";
  633. }
  634. else
  635. {
  636. var obj = document.getElementById('loader');
  637. if ( ! obj && typeof(process_request) != 'undefined')
  638. {
  639. obj = document.createElement("DIV");
  640. obj.id = "loader";
  641. obj.innerHTML = process_request;
  642. document.body.appendChild(obj);
  643. }
  644. }
  645. }
  646. /* *
  647. * 隐藏载入信息
  648. */
  649. function hideLoader()
  650. {
  651. document.getElementsByTagName('body').item(0).style.cursor = "auto";
  652. if (top.frames['header-frame'] && top.frames['header-frame'].document.getElementById("load-div"))
  653. {
  654. setTimeout(function(){top.frames['header-frame'].document.getElementById("load-div").style.display = "none"}, 10);
  655. }
  656. else
  657. {
  658. try
  659. {
  660. var obj = document.getElementById("loader");
  661. obj.style.display = 'none';
  662. document.body.removeChild(obj);
  663. }
  664. catch (ex)
  665. {}
  666. }
  667. }