WXForm.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. (function ($) {
  2. // 函数
  3. var ajaxSubmit = function (selector, callback) {
  4. var $form = $(selector);
  5. if ($form.attr('ajax-disabled') != undefined)
  6. return true;
  7. var options = {
  8. url: $form.attr('action') || window.location.href,
  9. type: $form.attr('method') || 'POST',
  10. beforeSend: function () {
  11. $.showLoading();
  12. },
  13. success: function (result) {
  14. if(callback && typeof(callback) === "function") {
  15. callback(result);
  16. }
  17. },
  18. complete: function() {
  19. $.hideLoading();
  20. }
  21. ,error:function(result){
  22. alert(JSON.stringify(result));
  23. }
  24. };
  25. if (!!$form.attr('enctype') && $form.attr('enctype').toLowerCase() === 'multipart/form-data') {
  26. var formData = new FormData();
  27. var $files = $form.find('input[type="file"][name]');
  28. $files.each(function() {
  29. if ('files' in this && this.files.length > 0) {
  30. // ToDo: Support Multiple on any input?
  31. // Just need a loop here..
  32. formData.append(this.name, this.files[0]);
  33. }
  34. });
  35. var $noFiles = $form.find(':not(input[type="file"])');
  36. $.each($noFiles.serializeArray(), function(i, pair) {
  37. formData.append(pair.name, pair.value);
  38. });
  39. options.data = formData;
  40. options.method = 'POST';
  41. options.contentType = false;
  42. options.processData = false;
  43. } else {
  44. options.data = $form.serializeArray();
  45. }
  46. $.ajax(options);
  47. };
  48. $.extend($.fn, {
  49. ajaxSubmit: function (callback) {
  50. $(this).form()
  51. $(document).off('submit', this.selector).on('submit', this.selector, function (e) {
  52. e.preventDefault();
  53. var $form = $(this);
  54. if ($form.attr('ajax-disabled') != undefined)
  55. return true;
  56. ajaxSubmit(this, callback);
  57. return false;
  58. });
  59. }
  60. })
  61. })(Zepto);