jquery.form.js 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519
  1. (function (factory) {
  2. "use strict";
  3. if (typeof define === 'function' && define.amd) {
  4. // using AMD; register as anon module
  5. define(['jquery'], factory);
  6. } else {
  7. // no AMD; invoke directly
  8. factory( (typeof(jQuery) != 'undefined') ? jQuery : window.Zepto );
  9. }
  10. }
  11. (function($) {
  12. "use strict";
  13. /*
  14. Usage Note:
  15. -----------
  16. Do not use both ajaxSubmit and ajaxForm on the same form. These
  17. functions are mutually exclusive. Use ajaxSubmit if you want
  18. to bind your own submit handler to the form. For example,
  19. $(document).ready(function() {
  20. $('#myForm').on('submit', function(e) {
  21. e.preventDefault(); // <-- important
  22. $(this).ajaxSubmit({
  23. target: '#output'
  24. });
  25. });
  26. });
  27. Use ajaxForm when you want the plugin to manage all the event binding
  28. for you. For example,
  29. $(document).ready(function() {
  30. $('#myForm').ajaxForm({
  31. target: '#output'
  32. });
  33. });
  34. You can also use ajaxForm with delegation (requires jQuery v1.7+), so the
  35. form does not have to exist when you invoke ajaxForm:
  36. $('#myForm').ajaxForm({
  37. delegation: true,
  38. target: '#output'
  39. });
  40. When using ajaxForm, the ajaxSubmit function will be invoked for you
  41. at the appropriate time.
  42. */
  43. /**
  44. * Feature detection
  45. */
  46. var feature = {};
  47. feature.fileapi = $("<input type='file'/>").get(0).files !== undefined;
  48. feature.formdata = window.FormData !== undefined;
  49. var hasProp = !!$.fn.prop;
  50. // attr2 uses prop when it can but checks the return type for
  51. // an expected string. this accounts for the case where a form
  52. // contains inputs with names like "action" or "method"; in those
  53. // cases "prop" returns the element
  54. $.fn.attr2 = function() {
  55. if ( ! hasProp ) {
  56. return this.attr.apply(this, arguments);
  57. }
  58. var val = this.prop.apply(this, arguments);
  59. if ( ( val && val.jquery ) || typeof val === 'string' ) {
  60. return val;
  61. }
  62. return this.attr.apply(this, arguments);
  63. };
  64. /**
  65. * ajaxSubmit() provides a mechanism for immediately submitting
  66. * an HTML form using AJAX.
  67. */
  68. $.fn.ajaxSubmit = function(options) {
  69. /*jshint scripturl:true */
  70. // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
  71. if (!this.length) {
  72. log('ajaxSubmit: skipping submit process - no element selected');
  73. return this;
  74. }
  75. var method, action, url, $form = this;
  76. if (typeof options == 'function') {
  77. options = { success: options };
  78. }
  79. else if ( options === undefined ) {
  80. options = {};
  81. }
  82. method = options.type || this.attr2('method');
  83. action = options.url || this.attr2('action');
  84. url = (typeof action === 'string') ? $.trim(action) : '';
  85. url = url || window.location.href || '';
  86. if (url) {
  87. // clean url (don't include hash vaue)
  88. url = (url.match(/^([^#]+)/)||[])[1];
  89. }
  90. options = $.extend(true, {
  91. url: url,
  92. success: $.ajaxSettings.success,
  93. type: method || $.ajaxSettings.type,
  94. iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
  95. }, options);
  96. // hook for manipulating the form data before it is extracted;
  97. // convenient for use with rich editors like tinyMCE or FCKEditor
  98. var veto = {};
  99. this.trigger('form-pre-serialize', [this, options, veto]);
  100. if (veto.veto) {
  101. log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
  102. return this;
  103. }
  104. // provide opportunity to alter form data before it is serialized
  105. if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
  106. log('ajaxSubmit: submit aborted via beforeSerialize callback');
  107. return this;
  108. }
  109. var traditional = options.traditional;
  110. if ( traditional === undefined ) {
  111. traditional = $.ajaxSettings.traditional;
  112. }
  113. var elements = [];
  114. var qx, a = this.formToArray(options.semantic, elements);
  115. if (options.data) {
  116. options.extraData = options.data;
  117. qx = $.param(options.data, traditional);
  118. }
  119. // give pre-submit callback an opportunity to abort the submit
  120. if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
  121. log('ajaxSubmit: submit aborted via beforeSubmit callback');
  122. return this;
  123. }
  124. // fire vetoable 'validate' event
  125. this.trigger('form-submit-validate', [a, this, options, veto]);
  126. if (veto.veto) {
  127. log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
  128. return this;
  129. }
  130. var q = $.param(a, traditional);
  131. if (qx) {
  132. q = ( q ? (q + '&' + qx) : qx );
  133. }
  134. if (options.type.toUpperCase() == 'GET') {
  135. options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
  136. options.data = null; // data is null for 'get'
  137. }
  138. else {
  139. options.data = q; // data is the query string for 'post'
  140. }
  141. var callbacks = [];
  142. if (options.resetForm) {
  143. callbacks.push(function() { $form.resetForm(); });
  144. }
  145. if (options.clearForm) {
  146. callbacks.push(function() { $form.clearForm(options.includeHidden); });
  147. }
  148. // perform a load on the target only if dataType is not provided
  149. if (!options.dataType && options.target) {
  150. var oldSuccess = options.success || function(){};
  151. callbacks.push(function(data) {
  152. var fn = options.replaceTarget ? 'replaceWith' : 'html';
  153. $(options.target)[fn](data).each(oldSuccess, arguments);
  154. });
  155. }
  156. else if (options.success) {
  157. callbacks.push(options.success);
  158. }
  159. options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
  160. var context = options.context || this ; // jQuery 1.4+ supports scope context
  161. for (var i=0, max=callbacks.length; i < max; i++) {
  162. callbacks[i].apply(context, [data, status, xhr || $form, $form]);
  163. }
  164. };
  165. if (options.error) {
  166. var oldError = options.error;
  167. options.error = function(xhr, status, error) {
  168. var context = options.context || this;
  169. oldError.apply(context, [xhr, status, error, $form]);
  170. };
  171. }
  172. if (options.complete) {
  173. var oldComplete = options.complete;
  174. options.complete = function(xhr, status) {
  175. var context = options.context || this;
  176. oldComplete.apply(context, [xhr, status, $form]);
  177. };
  178. }
  179. // are there files to upload?
  180. // [value] (issue #113), also see comment:
  181. // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219
  182. var fileInputs = $('input[type=file]:enabled', this).filter(function() { return $(this).val() !== ''; });
  183. var hasFileInputs = fileInputs.length > 0;
  184. var mp = 'multipart/form-data';
  185. var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
  186. var fileAPI = feature.fileapi && feature.formdata;
  187. log("fileAPI :" + fileAPI);
  188. var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;
  189. var jqxhr;
  190. // options.iframe allows user to force iframe mode
  191. // 06-NOV-09: now defaulting to iframe mode if file input is detected
  192. if (options.iframe !== false && (options.iframe || shouldUseFrame)) {
  193. // hack to fix Safari hang (thanks to Tim Molendijk for this)
  194. // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
  195. if (options.closeKeepAlive) {
  196. $.get(options.closeKeepAlive, function() {
  197. jqxhr = fileUploadIframe(a);
  198. });
  199. }
  200. else {
  201. jqxhr = fileUploadIframe(a);
  202. }
  203. }
  204. else if ((hasFileInputs || multipart) && fileAPI) {
  205. jqxhr = fileUploadXhr(a);
  206. }
  207. else {
  208. jqxhr = $.ajax(options);
  209. }
  210. $form.removeData('jqxhr').data('jqxhr', jqxhr);
  211. // clear element array
  212. for (var k=0; k < elements.length; k++) {
  213. elements[k] = null;
  214. }
  215. // fire 'notify' event
  216. this.trigger('form-submit-notify', [this, options]);
  217. return this;
  218. // utility fn for deep serialization
  219. function deepSerialize(extraData){
  220. var serialized = $.param(extraData, options.traditional).split('&');
  221. var len = serialized.length;
  222. var result = [];
  223. var i, part;
  224. for (i=0; i < len; i++) {
  225. // #252; undo param space replacement
  226. serialized[i] = serialized[i].replace(/\+/g,' ');
  227. part = serialized[i].split('=');
  228. // #278; use array instead of object storage, favoring array serializations
  229. result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]);
  230. }
  231. return result;
  232. }
  233. // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
  234. function fileUploadXhr(a) {
  235. var formdata = new FormData();
  236. for (var i=0; i < a.length; i++) {
  237. formdata.append(a[i].name, a[i].value);
  238. }
  239. if (options.extraData) {
  240. var serializedData = deepSerialize(options.extraData);
  241. for (i=0; i < serializedData.length; i++) {
  242. if (serializedData[i]) {
  243. formdata.append(serializedData[i][0], serializedData[i][1]);
  244. }
  245. }
  246. }
  247. options.data = null;
  248. var s = $.extend(true, {}, $.ajaxSettings, options, {
  249. contentType: false,
  250. processData: false,
  251. cache: false,
  252. type: method || 'POST'
  253. });
  254. if (options.uploadProgress) {
  255. // workaround because jqXHR does not expose upload property
  256. s.xhr = function() {
  257. var xhr = $.ajaxSettings.xhr();
  258. if (xhr.upload) {
  259. xhr.upload.addEventListener('progress', function(event) {
  260. var percent = 0;
  261. var position = event.loaded || event.position; /*event.position is deprecated*/
  262. var total = event.total;
  263. if (event.lengthComputable) {
  264. percent = Math.ceil(position / total * 100);
  265. }
  266. options.uploadProgress(event, position, total, percent);
  267. }, false);
  268. }
  269. return xhr;
  270. };
  271. }
  272. s.data = null;
  273. var beforeSend = s.beforeSend;
  274. s.beforeSend = function(xhr, o) {
  275. //Send FormData() provided by user
  276. if (options.formData) {
  277. o.data = options.formData;
  278. }
  279. else {
  280. o.data = formdata;
  281. }
  282. if(beforeSend) {
  283. beforeSend.call(this, xhr, o);
  284. }
  285. };
  286. return $.ajax(s);
  287. }
  288. // private function for handling file uploads (hat tip to YAHOO!)
  289. function fileUploadIframe(a) {
  290. var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
  291. var deferred = $.Deferred();
  292. // #341
  293. deferred.abort = function(status) {
  294. xhr.abort(status);
  295. };
  296. if (a) {
  297. // ensure that every serialized input is still enabled
  298. for (i=0; i < elements.length; i++) {
  299. el = $(elements[i]);
  300. if ( hasProp ) {
  301. el.prop('disabled', false);
  302. }
  303. else {
  304. el.removeAttr('disabled');
  305. }
  306. }
  307. }
  308. s = $.extend(true, {}, $.ajaxSettings, options);
  309. s.context = s.context || s;
  310. id = 'jqFormIO' + (new Date().getTime());
  311. if (s.iframeTarget) {
  312. $io = $(s.iframeTarget);
  313. n = $io.attr2('name');
  314. if (!n) {
  315. $io.attr2('name', id);
  316. }
  317. else {
  318. id = n;
  319. }
  320. }
  321. else {
  322. $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
  323. $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
  324. }
  325. io = $io[0];
  326. xhr = { // mock object
  327. aborted: 0,
  328. responseText: null,
  329. responseXML: null,
  330. status: 0,
  331. statusText: 'n/a',
  332. getAllResponseHeaders: function() {},
  333. getResponseHeader: function() {},
  334. setRequestHeader: function() {},
  335. abort: function(status) {
  336. var e = (status === 'timeout' ? 'timeout' : 'aborted');
  337. log('aborting upload... ' + e);
  338. this.aborted = 1;
  339. try { // #214, #257
  340. if (io.contentWindow.document.execCommand) {
  341. io.contentWindow.document.execCommand('Stop');
  342. }
  343. }
  344. catch(ignore) {}
  345. $io.attr('src', s.iframeSrc); // abort op in progress
  346. xhr.error = e;
  347. if (s.error) {
  348. s.error.call(s.context, xhr, e, status);
  349. }
  350. if (g) {
  351. $.event.trigger("ajaxError", [xhr, s, e]);
  352. }
  353. if (s.complete) {
  354. s.complete.call(s.context, xhr, e);
  355. }
  356. }
  357. };
  358. g = s.global;
  359. // trigger ajax global events so that activity/block indicators work like normal
  360. if (g && 0 === $.active++) {
  361. $.event.trigger("ajaxStart");
  362. }
  363. if (g) {
  364. $.event.trigger("ajaxSend", [xhr, s]);
  365. }
  366. if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
  367. if (s.global) {
  368. $.active--;
  369. }
  370. deferred.reject();
  371. return deferred;
  372. }
  373. if (xhr.aborted) {
  374. deferred.reject();
  375. return deferred;
  376. }
  377. // add submitting element to data if we know it
  378. sub = form.clk;
  379. if (sub) {
  380. n = sub.name;
  381. if (n && !sub.disabled) {
  382. s.extraData = s.extraData || {};
  383. s.extraData[n] = sub.value;
  384. if (sub.type == "image") {
  385. s.extraData[n+'.x'] = form.clk_x;
  386. s.extraData[n+'.y'] = form.clk_y;
  387. }
  388. }
  389. }
  390. var CLIENT_TIMEOUT_ABORT = 1;
  391. var SERVER_ABORT = 2;
  392. function getDoc(frame) {
  393. /* it looks like contentWindow or contentDocument do not
  394. * carry the protocol property in ie8, when running under ssl
  395. * frame.document is the only valid response document, since
  396. * the protocol is know but not on the other two objects. strange?
  397. * "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy
  398. */
  399. var doc = null;
  400. // IE8 cascading access check
  401. try {
  402. if (frame.contentWindow) {
  403. doc = frame.contentWindow.document;
  404. }
  405. } catch(err) {
  406. // IE8 access denied under ssl & missing protocol
  407. log('cannot get iframe.contentWindow document: ' + err);
  408. }
  409. if (doc) { // successful getting content
  410. return doc;
  411. }
  412. try { // simply checking may throw in ie8 under ssl or mismatched protocol
  413. doc = frame.contentDocument ? frame.contentDocument : frame.document;
  414. } catch(err) {
  415. // last attempt
  416. log('cannot get iframe.contentDocument: ' + err);
  417. doc = frame.document;
  418. }
  419. return doc;
  420. }
  421. // Rails CSRF hack (thanks to Yvan Barthelemy)
  422. var csrf_token = $('meta[name=csrf-token]').attr('content');
  423. var csrf_param = $('meta[name=csrf-param]').attr('content');
  424. if (csrf_param && csrf_token) {
  425. s.extraData = s.extraData || {};
  426. s.extraData[csrf_param] = csrf_token;
  427. }
  428. // take a breath so that pending repaints get some cpu time before the upload starts
  429. function doSubmit() {
  430. // make sure form attrs are set
  431. var t = $form.attr2('target'),
  432. a = $form.attr2('action'),
  433. mp = 'multipart/form-data',
  434. et = $form.attr('enctype') || $form.attr('encoding') || mp;
  435. // update form attrs in IE friendly way
  436. form.setAttribute('target',id);
  437. if (!method || /post/i.test(method) ) {
  438. form.setAttribute('method', 'POST');
  439. }
  440. if (a != s.url) {
  441. form.setAttribute('action', s.url);
  442. }
  443. // ie borks in some cases when setting encoding
  444. if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
  445. $form.attr({
  446. encoding: 'multipart/form-data',
  447. enctype: 'multipart/form-data'
  448. });
  449. }
  450. // support timout
  451. if (s.timeout) {
  452. timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
  453. }
  454. // look for server aborts
  455. function checkState() {
  456. try {
  457. var state = getDoc(io).readyState;
  458. log('state = ' + state);
  459. if (state && state.toLowerCase() == 'uninitialized') {
  460. setTimeout(checkState,50);
  461. }
  462. }
  463. catch(e) {
  464. log('Server abort: ' , e, ' (', e.name, ')');
  465. cb(SERVER_ABORT);
  466. if (timeoutHandle) {
  467. clearTimeout(timeoutHandle);
  468. }
  469. timeoutHandle = undefined;
  470. }
  471. }
  472. // add "extra" data to form if provided in options
  473. var extraInputs = [];
  474. try {
  475. if (s.extraData) {
  476. for (var n in s.extraData) {
  477. if (s.extraData.hasOwnProperty(n)) {
  478. // if using the $.param format that allows for multiple values with the same name
  479. if($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) {
  480. extraInputs.push(
  481. $('<input type="hidden" name="'+s.extraData[n].name+'">').val(s.extraData[n].value)
  482. .appendTo(form)[0]);
  483. } else {
  484. extraInputs.push(
  485. $('<input type="hidden" name="'+n+'">').val(s.extraData[n])
  486. .appendTo(form)[0]);
  487. }
  488. }
  489. }
  490. }
  491. if (!s.iframeTarget) {
  492. // add iframe to doc and submit the form
  493. $io.appendTo('body');
  494. }
  495. if (io.attachEvent) {
  496. io.attachEvent('onload', cb);
  497. }
  498. else {
  499. io.addEventListener('load', cb, false);
  500. }
  501. setTimeout(checkState,15);
  502. try {
  503. form.submit();
  504. } catch(err) {
  505. // just in case form has element with name/id of 'submit'
  506. var submitFn = document.createElement('form').submit;
  507. submitFn.apply(form);
  508. }
  509. }
  510. finally {
  511. // reset attrs and remove "extra" input elements
  512. form.setAttribute('action',a);
  513. form.setAttribute('enctype', et); // #380
  514. if(t) {
  515. form.setAttribute('target', t);
  516. } else {
  517. $form.removeAttr('target');
  518. }
  519. $(extraInputs).remove();
  520. }
  521. }
  522. if (s.forceSync) {
  523. doSubmit();
  524. }
  525. else {
  526. setTimeout(doSubmit, 10); // this lets dom updates render
  527. }
  528. var data, doc, domCheckCount = 50, callbackProcessed;
  529. function cb(e) {
  530. if (xhr.aborted || callbackProcessed) {
  531. return;
  532. }
  533. doc = getDoc(io);
  534. if(!doc) {
  535. log('cannot access response document');
  536. e = SERVER_ABORT;
  537. }
  538. if (e === CLIENT_TIMEOUT_ABORT && xhr) {
  539. xhr.abort('timeout');
  540. deferred.reject(xhr, 'timeout');
  541. return;
  542. }
  543. else if (e == SERVER_ABORT && xhr) {
  544. xhr.abort('server abort');
  545. deferred.reject(xhr, 'error', 'server abort');
  546. return;
  547. }
  548. if (!doc || doc.location.href == s.iframeSrc) {
  549. // response not received yet
  550. if (!timedOut) {
  551. return;
  552. }
  553. }
  554. if (io.detachEvent) {
  555. io.detachEvent('onload', cb);
  556. }
  557. else {
  558. io.removeEventListener('load', cb, false);
  559. }
  560. var status = 'success', errMsg;
  561. try {
  562. if (timedOut) {
  563. throw 'timeout';
  564. }
  565. var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
  566. log('isXml='+isXml);
  567. if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) {
  568. if (--domCheckCount) {
  569. // in some browsers (Opera) the iframe DOM is not always traversable when
  570. // the onload callback fires, so we loop a bit to accommodate
  571. log('requeing onLoad callback, DOM not available');
  572. setTimeout(cb, 250);
  573. return;
  574. }
  575. // let this fall through because server response could be an empty document
  576. //log('Could not access iframe DOM after mutiple tries.');
  577. //throw 'DOMException: not available';
  578. }
  579. //log('response detected');
  580. var docRoot = doc.body ? doc.body : doc.documentElement;
  581. xhr.responseText = docRoot ? docRoot.innerHTML : null;
  582. xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
  583. if (isXml) {
  584. s.dataType = 'xml';
  585. }
  586. xhr.getResponseHeader = function(header){
  587. var headers = {'content-type': s.dataType};
  588. return headers[header.toLowerCase()];
  589. };
  590. // support for XHR 'status' & 'statusText' emulation :
  591. if (docRoot) {
  592. xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
  593. xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
  594. }
  595. var dt = (s.dataType || '').toLowerCase();
  596. var scr = /(json|script|text)/.test(dt);
  597. if (scr || s.textarea) {
  598. // see if user embedded response in textarea
  599. var ta = doc.getElementsByTagName('textarea')[0];
  600. if (ta) {
  601. xhr.responseText = ta.value;
  602. // support for XHR 'status' & 'statusText' emulation :
  603. xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
  604. xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
  605. }
  606. else if (scr) {
  607. // account for browsers injecting pre around json response
  608. var pre = doc.getElementsByTagName('pre')[0];
  609. var b = doc.getElementsByTagName('body')[0];
  610. if (pre) {
  611. xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
  612. }
  613. else if (b) {
  614. xhr.responseText = b.textContent ? b.textContent : b.innerText;
  615. }
  616. }
  617. }
  618. else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) {
  619. xhr.responseXML = toXml(xhr.responseText);
  620. }
  621. try {
  622. data = httpData(xhr, dt, s);
  623. }
  624. catch (err) {
  625. status = 'parsererror';
  626. xhr.error = errMsg = (err || status);
  627. }
  628. }
  629. catch (err) {
  630. log('error caught: ',err);
  631. status = 'error';
  632. xhr.error = errMsg = (err || status);
  633. }
  634. if (xhr.aborted) {
  635. log('upload aborted');
  636. status = null;
  637. }
  638. if (xhr.status) { // we've set xhr.status
  639. status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
  640. }
  641. // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
  642. if (status === 'success') {
  643. if (s.success) {
  644. s.success.call(s.context, data, 'success', xhr);
  645. }
  646. deferred.resolve(xhr.responseText, 'success', xhr);
  647. if (g) {
  648. $.event.trigger("ajaxSuccess", [xhr, s]);
  649. }
  650. }
  651. else if (status) {
  652. if (errMsg === undefined) {
  653. errMsg = xhr.statusText;
  654. }
  655. if (s.error) {
  656. s.error.call(s.context, xhr, status, errMsg);
  657. }
  658. deferred.reject(xhr, 'error', errMsg);
  659. if (g) {
  660. $.event.trigger("ajaxError", [xhr, s, errMsg]);
  661. }
  662. }
  663. if (g) {
  664. $.event.trigger("ajaxComplete", [xhr, s]);
  665. }
  666. if (g && ! --$.active) {
  667. $.event.trigger("ajaxStop");
  668. }
  669. if (s.complete) {
  670. s.complete.call(s.context, xhr, status);
  671. }
  672. callbackProcessed = true;
  673. if (s.timeout) {
  674. clearTimeout(timeoutHandle);
  675. }
  676. // clean up
  677. setTimeout(function() {
  678. if (!s.iframeTarget) {
  679. $io.remove();
  680. }
  681. else { //adding else to clean up existing iframe response.
  682. $io.attr('src', s.iframeSrc);
  683. }
  684. xhr.responseXML = null;
  685. }, 100);
  686. }
  687. var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
  688. if (window.ActiveXObject) {
  689. doc = new ActiveXObject('Microsoft.XMLDOM');
  690. doc.async = 'false';
  691. doc.loadXML(s);
  692. }
  693. else {
  694. doc = (new DOMParser()).parseFromString(s, 'text/xml');
  695. }
  696. return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
  697. };
  698. var parseJSON = $.parseJSON || function(s) {
  699. /*jslint evil:true */
  700. return window['eval']('(' + s + ')');
  701. };
  702. var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4
  703. var ct = xhr.getResponseHeader('content-type') || '',
  704. xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
  705. data = xml ? xhr.responseXML : xhr.responseText;
  706. if (xml && data.documentElement.nodeName === 'parsererror') {
  707. if ($.error) {
  708. $.error('parsererror');
  709. }
  710. }
  711. if (s && s.dataFilter) {
  712. data = s.dataFilter(data, type);
  713. }
  714. if (typeof data === 'string') {
  715. if (type === 'json' || !type && ct.indexOf('json') >= 0) {
  716. data = parseJSON(data);
  717. } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
  718. $.globalEval(data);
  719. }
  720. }
  721. return data;
  722. };
  723. return deferred;
  724. }
  725. };
  726. /**
  727. * ajaxForm() provides a mechanism for fully automating form submission.
  728. *
  729. * The advantages of using this method instead of ajaxSubmit() are:
  730. *
  731. * 1: This method will include coordinates for <input type="image" /> elements (if the element
  732. * is used to submit the form).
  733. * 2. This method will include the submit element's name/value data (for the element that was
  734. * used to submit the form).
  735. * 3. This method binds the submit() method to the form for you.
  736. *
  737. * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
  738. * passes the options argument along after properly binding events for submit elements and
  739. * the form itself.
  740. */
  741. $.fn.ajaxForm = function(options) {
  742. options = options || {};
  743. options.delegation = options.delegation && $.isFunction($.fn.on);
  744. // in jQuery 1.3+ we can fix mistakes with the ready state
  745. if (!options.delegation && this.length === 0) {
  746. var o = { s: this.selector, c: this.context };
  747. if (!$.isReady && o.s) {
  748. log('DOM not ready, queuing ajaxForm');
  749. $(function() {
  750. $(o.s,o.c).ajaxForm(options);
  751. });
  752. return this;
  753. }
  754. // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
  755. log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
  756. return this;
  757. }
  758. if ( options.delegation ) {
  759. $(document)
  760. .off('submit.form-plugin', this.selector, doAjaxSubmit)
  761. .off('click.form-plugin', this.selector, captureSubmittingElement)
  762. .on('submit.form-plugin', this.selector, options, doAjaxSubmit)
  763. .on('click.form-plugin', this.selector, options, captureSubmittingElement);
  764. return this;
  765. }
  766. return this.ajaxFormUnbind()
  767. .bind('submit.form-plugin', options, doAjaxSubmit)
  768. .bind('click.form-plugin', options, captureSubmittingElement);
  769. };
  770. // private event handlers
  771. function doAjaxSubmit(e) {
  772. /*jshint validthis:true */
  773. var options = e.data;
  774. if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
  775. e.preventDefault();
  776. $(e.target).ajaxSubmit(options); // #365
  777. }
  778. }
  779. function captureSubmittingElement(e) {
  780. /*jshint validthis:true */
  781. var target = e.target;
  782. var $el = $(target);
  783. if (!($el.is("[type=submit],[type=image]"))) {
  784. // is this a child element of the submit el? (ex: a span within a button)
  785. var t = $el.closest('[type=submit]');
  786. if (t.length === 0) {
  787. return;
  788. }
  789. target = t[0];
  790. }
  791. var form = this;
  792. form.clk = target;
  793. if (target.type == 'image') {
  794. if (e.offsetX !== undefined) {
  795. form.clk_x = e.offsetX;
  796. form.clk_y = e.offsetY;
  797. } else if (typeof $.fn.offset == 'function') {
  798. var offset = $el.offset();
  799. form.clk_x = e.pageX - offset.left;
  800. form.clk_y = e.pageY - offset.top;
  801. } else {
  802. form.clk_x = e.pageX - target.offsetLeft;
  803. form.clk_y = e.pageY - target.offsetTop;
  804. }
  805. }
  806. // clear form vars
  807. setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
  808. }
  809. // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
  810. $.fn.ajaxFormUnbind = function() {
  811. return this.unbind('submit.form-plugin click.form-plugin');
  812. };
  813. /**
  814. * formToArray() gathers form element data into an array of objects that can
  815. * be passed to any of the following ajax functions: $.get, $.post, or load.
  816. * Each object in the array has both a 'name' and 'value' property. An example of
  817. * an array for a simple login form might be:
  818. *
  819. * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
  820. *
  821. * It is this array that is passed to pre-submit callback functions provided to the
  822. * ajaxSubmit() and ajaxForm() methods.
  823. */
  824. $.fn.formToArray = function(semantic, elements) {
  825. var a = [];
  826. if (this.length === 0) {
  827. return a;
  828. }
  829. var form = this[0];
  830. var formId = this.attr('id');
  831. var els = semantic ? form.getElementsByTagName('*') : form.elements;
  832. var els2;
  833. if (els && !/MSIE [678]/.test(navigator.userAgent)) { // #390
  834. els = $(els).get(); // convert to standard array
  835. }
  836. // #386; account for inputs outside the form which use the 'form' attribute
  837. if ( formId ) {
  838. els2 = $(':input[form=' + formId + ']').get();
  839. if ( els2.length ) {
  840. els = (els || []).concat(els2);
  841. }
  842. }
  843. if (!els || !els.length) {
  844. return a;
  845. }
  846. var i,j,n,v,el,max,jmax;
  847. for(i=0, max=els.length; i < max; i++) {
  848. el = els[i];
  849. n = el.name;
  850. if (!n || el.disabled) {
  851. continue;
  852. }
  853. if (semantic && form.clk && el.type == "image") {
  854. // handle image inputs on the fly when semantic == true
  855. if(form.clk == el) {
  856. a.push({name: n, value: $(el).val(), type: el.type });
  857. a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
  858. }
  859. continue;
  860. }
  861. v = $.fieldValue(el, true);
  862. if (v && v.constructor == Array) {
  863. if (elements) {
  864. elements.push(el);
  865. }
  866. for(j=0, jmax=v.length; j < jmax; j++) {
  867. a.push({name: n, value: v[j]});
  868. }
  869. }
  870. else if (feature.fileapi && el.type == 'file') {
  871. if (elements) {
  872. elements.push(el);
  873. }
  874. var files = el.files;
  875. if (files.length) {
  876. for (j=0; j < files.length; j++) {
  877. a.push({name: n, value: files[j], type: el.type});
  878. }
  879. }
  880. else {
  881. // #180
  882. a.push({ name: n, value: '', type: el.type });
  883. }
  884. }
  885. else if (v !== null && typeof v != 'undefined') {
  886. if (elements) {
  887. elements.push(el);
  888. }
  889. a.push({name: n, value: v, type: el.type, required: el.required});
  890. }
  891. }
  892. if (!semantic && form.clk) {
  893. // input type=='image' are not found in elements array! handle it here
  894. var $input = $(form.clk), input = $input[0];
  895. n = input.name;
  896. if (n && !input.disabled && input.type == 'image') {
  897. a.push({name: n, value: $input.val()});
  898. a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
  899. }
  900. }
  901. return a;
  902. };
  903. /**
  904. * Serializes form data into a 'submittable' string. This method will return a string
  905. * in the format: name1=value1&amp;name2=value2
  906. */
  907. $.fn.formSerialize = function(semantic) {
  908. //hand off to jQuery.param for proper encoding
  909. return $.param(this.formToArray(semantic));
  910. };
  911. /**
  912. * Serializes all field elements in the jQuery object into a query string.
  913. * This method will return a string in the format: name1=value1&amp;name2=value2
  914. */
  915. $.fn.fieldSerialize = function(successful) {
  916. var a = [];
  917. this.each(function() {
  918. var n = this.name;
  919. if (!n) {
  920. return;
  921. }
  922. var v = $.fieldValue(this, successful);
  923. if (v && v.constructor == Array) {
  924. for (var i=0,max=v.length; i < max; i++) {
  925. a.push({name: n, value: v[i]});
  926. }
  927. }
  928. else if (v !== null && typeof v != 'undefined') {
  929. a.push({name: this.name, value: v});
  930. }
  931. });
  932. //hand off to jQuery.param for proper encoding
  933. return $.param(a);
  934. };
  935. /**
  936. * Returns the value(s) of the element in the matched set. For example, consider the following form:
  937. *
  938. * <form><fieldset>
  939. * <input name="A" type="text" />
  940. * <input name="A" type="text" />
  941. * <input name="B" type="checkbox" value="B1" />
  942. * <input name="B" type="checkbox" value="B2"/>
  943. * <input name="C" type="radio" value="C1" />
  944. * <input name="C" type="radio" value="C2" />
  945. * </fieldset></form>
  946. *
  947. * var v = $('input[type=text]').fieldValue();
  948. * // if no values are entered into the text inputs
  949. * v == ['','']
  950. * // if values entered into the text inputs are 'foo' and 'bar'
  951. * v == ['foo','bar']
  952. *
  953. * var v = $('input[type=checkbox]').fieldValue();
  954. * // if neither checkbox is checked
  955. * v === undefined
  956. * // if both checkboxes are checked
  957. * v == ['B1', 'B2']
  958. *
  959. * var v = $('input[type=radio]').fieldValue();
  960. * // if neither radio is checked
  961. * v === undefined
  962. * // if first radio is checked
  963. * v == ['C1']
  964. *
  965. * The successful argument controls whether or not the field element must be 'successful'
  966. * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
  967. * The default value of the successful argument is true. If this value is false the value(s)
  968. * for each element is returned.
  969. *
  970. * Note: This method *always* returns an array. If no valid value can be determined the
  971. * array will be empty, otherwise it will contain one or more values.
  972. */
  973. $.fn.fieldValue = function(successful) {
  974. for (var val=[], i=0, max=this.length; i < max; i++) {
  975. var el = this[i];
  976. var v = $.fieldValue(el, successful);
  977. if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
  978. continue;
  979. }
  980. if (v.constructor == Array) {
  981. $.merge(val, v);
  982. }
  983. else {
  984. val.push(v);
  985. }
  986. }
  987. return val;
  988. };
  989. /**
  990. * Returns the value of the field element.
  991. */
  992. $.fieldValue = function(el, successful) {
  993. var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
  994. if (successful === undefined) {
  995. successful = true;
  996. }
  997. if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
  998. (t == 'checkbox' || t == 'radio') && !el.checked ||
  999. (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
  1000. tag == 'select' && el.selectedIndex == -1)) {
  1001. return null;
  1002. }
  1003. if (tag == 'select') {
  1004. var index = el.selectedIndex;
  1005. if (index < 0) {
  1006. return null;
  1007. }
  1008. var a = [], ops = el.options;
  1009. var one = (t == 'select-one');
  1010. var max = (one ? index+1 : ops.length);
  1011. for(var i=(one ? index : 0); i < max; i++) {
  1012. var op = ops[i];
  1013. if (op.selected) {
  1014. var v = op.value;
  1015. if (!v) { // extra pain for IE...
  1016. v = (op.attributes && op.attributes.value && !(op.attributes.value.specified)) ? op.text : op.value;
  1017. }
  1018. if (one) {
  1019. return v;
  1020. }
  1021. a.push(v);
  1022. }
  1023. }
  1024. return a;
  1025. }
  1026. return $(el).val();
  1027. };
  1028. /**
  1029. * Clears the form data. Takes the following actions on the form's input fields:
  1030. * - input text fields will have their 'value' property set to the empty string
  1031. * - select elements will have their 'selectedIndex' property set to -1
  1032. * - checkbox and radio inputs will have their 'checked' property set to false
  1033. * - inputs of type submit, button, reset, and hidden will *not* be effected
  1034. * - button elements will *not* be effected
  1035. */
  1036. $.fn.clearForm = function(includeHidden) {
  1037. return this.each(function() {
  1038. $('input,select,textarea', this).clearFields(includeHidden);
  1039. });
  1040. };
  1041. /**
  1042. * Clears the selected form elements.
  1043. */
  1044. $.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
  1045. var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
  1046. return this.each(function() {
  1047. var t = this.type, tag = this.tagName.toLowerCase();
  1048. if (re.test(t) || tag == 'textarea') {
  1049. this.value = '';
  1050. }
  1051. else if (t == 'checkbox' || t == 'radio') {
  1052. this.checked = false;
  1053. }
  1054. else if (tag == 'select') {
  1055. this.selectedIndex = -1;
  1056. }
  1057. else if (t == "file") {
  1058. if (/MSIE/.test(navigator.userAgent)) {
  1059. $(this).replaceWith($(this).clone(true));
  1060. } else {
  1061. $(this).val('');
  1062. }
  1063. }
  1064. else if (includeHidden) {
  1065. // includeHidden can be the value true, or it can be a selector string
  1066. // indicating a special test; for example:
  1067. // $('#myForm').clearForm('.special:hidden')
  1068. // the above would clean hidden inputs that have the class of 'special'
  1069. if ( (includeHidden === true && /hidden/.test(t)) ||
  1070. (typeof includeHidden == 'string' && $(this).is(includeHidden)) ) {
  1071. this.value = '';
  1072. }
  1073. }
  1074. });
  1075. };
  1076. /**
  1077. * Resets the form data. Causes all form elements to be reset to their original value.
  1078. */
  1079. $.fn.resetForm = function() {
  1080. return this.each(function() {
  1081. // guard against an input with the name of 'reset'
  1082. // note that IE reports the reset function as an 'object'
  1083. if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
  1084. this.reset();
  1085. }
  1086. });
  1087. };
  1088. /**
  1089. * Enables or disables any matching elements.
  1090. */
  1091. $.fn.enable = function(b) {
  1092. if (b === undefined) {
  1093. b = true;
  1094. }
  1095. return this.each(function() {
  1096. this.disabled = !b;
  1097. });
  1098. };
  1099. /**
  1100. * Checks/unchecks any matching checkboxes or radio buttons and
  1101. * selects/deselects and matching option elements.
  1102. */
  1103. $.fn.selected = function(select) {
  1104. if (select === undefined) {
  1105. select = true;
  1106. }
  1107. return this.each(function() {
  1108. var t = this.type;
  1109. if (t == 'checkbox' || t == 'radio') {
  1110. this.checked = select;
  1111. }
  1112. else if (this.tagName.toLowerCase() == 'option') {
  1113. var $sel = $(this).parent('select');
  1114. if (select && $sel[0] && $sel[0].type == 'select-one') {
  1115. // deselect all other options
  1116. $sel.find('option').selected(false);
  1117. }
  1118. this.selected = select;
  1119. }
  1120. });
  1121. };
  1122. // expose debug var
  1123. $.fn.ajaxSubmit.debug = false;
  1124. //从按钮ajax提交按钮所在的表单
  1125. $.fn.submitForm = function(options)
  1126. {
  1127. var opt = options || {};
  1128. opt.dataType = opt.dataType || 'json';
  1129. //
  1130. if (typeof opt.showRunning == 'undefined') opt.showRunning = true;
  1131. opt.success = function(fn, btn)
  1132. {
  1133. return function(data, frm)
  1134. {
  1135. try
  1136. {
  1137. if (fn)
  1138. {
  1139. return fn(data, frm);
  1140. }
  1141. } catch (e) { }
  1142. };
  1143. } (opt.success, this);
  1144. var btn = this;
  1145. opt.complete = function(XMLHttpRequest, textStatus, errorThrown)
  1146. {
  1147. if (textStatus != 'success')
  1148. {
  1149. }
  1150. }
  1151. opt.beforeSubmit = function(fn, btn)
  1152. {
  1153. return function(data, frm)
  1154. {
  1155. var willSubmit = false;
  1156. try
  1157. {
  1158. if (fn)
  1159. {
  1160. willSubmit = fn(data, frm);
  1161. } else
  1162. {
  1163. willSubmit = true;
  1164. }
  1165. } catch (e) { }
  1166. return willSubmit;
  1167. };
  1168. } (opt.beforeSubmit, this);
  1169. var form =opt.formID?$('#'+opt.formID):this.closest('form');// var form = this.closest('form');
  1170. form.ajaxSubmit(opt);
  1171. return this;
  1172. }
  1173. //给表单中可能出现的文本框绑定回车事件,当回车时执行某个方法,并返回false以阻止提交表单
  1174. $.fn.liveEnter = function(fn)
  1175. {
  1176. this.live(':text').keydown(function(event)
  1177. {
  1178. var e = $.event.fix(event);
  1179. if (e.keyCode == 13)
  1180. {
  1181. if ($.isFunction(fn))
  1182. {
  1183. try
  1184. {
  1185. fn();
  1186. } catch (e) { }
  1187. }
  1188. return false;
  1189. }
  1190. return true;
  1191. });
  1192. }
  1193. //给表单中的文本框绑定回车事件,当回车时执行某个方法,并返回false以阻止提交表单
  1194. $.fn.bindEnter = function(fn)
  1195. {
  1196. this.find(':text').keydown(function(event)
  1197. {
  1198. var e = $.event.fix(event);
  1199. if (e.keyCode == 13)
  1200. {
  1201. try
  1202. {
  1203. if ($.isFunction(fn))
  1204. {
  1205. fn();
  1206. }
  1207. } catch (e) { }
  1208. return false;
  1209. }
  1210. return true;
  1211. });
  1212. };
  1213. $.fn.proxyClick = function(btn)
  1214. {
  1215. try
  1216. {
  1217. if (typeof btn == 'string')
  1218. {
  1219. btn = $(btn);
  1220. }
  1221. btn.click();
  1222. } catch (e) { }
  1223. return false;
  1224. };
  1225. $.fn.selectedText = function()
  1226. {
  1227. return this.find('option[value=' + this.val() + ']').text();
  1228. }
  1229. //调用 $.getJSON方法去获取数据
  1230. //url--请求的地址
  1231. //data--要传递的参数
  1232. //callback成功的回调
  1233. //error--失败的回调
  1234. $.fn.getJSON = function(url, data, callback, error, async)
  1235. {
  1236. var success = callback;
  1237. var errorFn = null;
  1238. var complete = null;
  1239. var d = data;
  1240. if (typeof data == 'function')
  1241. {
  1242. success = data;
  1243. error = callback;
  1244. async = error;
  1245. d = {};
  1246. }
  1247. if (typeof error == 'boolean')
  1248. {
  1249. async = error;
  1250. }
  1251. if (async == 'undefined')
  1252. {
  1253. async = true;
  1254. }
  1255. success = function(fn, btn)
  1256. {
  1257. return function(json)
  1258. {
  1259. try
  1260. {
  1261. if (fn)
  1262. {
  1263. return fn(json);
  1264. }
  1265. } catch (e)
  1266. {
  1267. //alert(e.message);
  1268. }
  1269. };
  1270. } (success, this);
  1271. complete = function(btn)
  1272. {
  1273. return function(XMLHttpRequest, textStatus)
  1274. {
  1275. };
  1276. } (this);
  1277. errorFn = function(XMLHttpRequest, textStatus, errorThrown)
  1278. {
  1279. if (textStatus == 'error')
  1280. {
  1281. //alert(XMLHttpRequest.status);
  1282. }
  1283. if (error)
  1284. {
  1285. error(XMLHttpRequest, textStatus, errorThrown);
  1286. } else
  1287. {
  1288. $.showError();
  1289. }
  1290. };
  1291. this.running();
  1292. $.ajax({
  1293. type: "GET",
  1294. url: url,
  1295. dataType: "json",
  1296. data: d,
  1297. async: async,
  1298. success: success,
  1299. error: errorFn,
  1300. complete: complete
  1301. });
  1302. };
  1303. //调用 $.get方法去获取数据
  1304. //url--请求的地址
  1305. //data--要传递的参数
  1306. //callback成功的回调
  1307. //error--失败的回调
  1308. $.fn.getHTML = function(url, data, callback, error)
  1309. {
  1310. var success = callback;
  1311. var errorFn = null;
  1312. var complete = null;
  1313. var d = data;
  1314. if (typeof data == 'function')
  1315. {
  1316. success = data;
  1317. error = callback;
  1318. d = {};
  1319. }
  1320. success = function(fn, btn)
  1321. {
  1322. return function(json)
  1323. {
  1324. try
  1325. {
  1326. if (fn)
  1327. {
  1328. return fn(json);
  1329. }
  1330. } catch (e) { alert(e.message); }
  1331. };
  1332. } (success, this);
  1333. complete = function(btn)
  1334. {
  1335. return function(XMLHttpRequest, textStatus)
  1336. {
  1337. };
  1338. } (this);
  1339. errorFn = function(XMLHttpRequest, textStatus, errorThrown)
  1340. {
  1341. if (textStatus == 'error')
  1342. {
  1343. alert(XMLHttpRequest.status);
  1344. }
  1345. if (error)
  1346. {
  1347. error(XMLHttpRequest, textStatus, errorThrown);
  1348. }
  1349. };
  1350. this.running();
  1351. $.ajax({
  1352. type: "GET",
  1353. url: url,
  1354. dataType: "html",
  1355. data: d,
  1356. success: success,
  1357. error: errorFn,
  1358. complete: complete
  1359. });
  1360. }
  1361. // helper fn for console logging
  1362. function log() {
  1363. if (!$.fn.ajaxSubmit.debug) {
  1364. return;
  1365. }
  1366. var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
  1367. if (window.console && window.console.log) {
  1368. window.console.log(msg);
  1369. }
  1370. else if (window.opera && window.opera.postError) {
  1371. window.opera.postError(msg);
  1372. }
  1373. }
  1374. }));