form.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. !function(dependencies,factory){
  2. // amd || cmd
  3. if(typeof define == 'function' && (define.cmd || define.amd)) {
  4. define(dependencies,function() {
  5. return factory();
  6. });
  7. }
  8. else {
  9. var ex = factory();
  10. // CommonJS NodeJS
  11. if(typeof module !== 'undefined' && typeof exports === 'object') {
  12. module.exports = ex;
  13. }
  14. }
  15. }(['jquery'],function(){
  16. // 函数
  17. var ajaxSubmit = function(selector,callback) {
  18. var $form = $(selector);
  19. if ($form.attr('ajax-disabled') != undefined)
  20. return true;
  21. var options = {
  22. url: $form.attr('action') || window.location.href,
  23. type: $form.attr('method') || 'POST',
  24. beforeSend: function() {
  25. layer.load(2);
  26. },
  27. success: function(result) {
  28. if(callback && typeof(callback) === "function") {
  29. callback(result);
  30. }
  31. },
  32. complete: function() {
  33. layer.closeAll('loading');
  34. }
  35. ,error:function(result){
  36. alert(JSON.stringify(result));
  37. }
  38. };
  39. if (!!$form.attr('enctype') && $form.attr('enctype').toLowerCase() === 'multipart/form-data') {
  40. var formData = new FormData();
  41. var $files = $form.find('input[type="file"][name]');
  42. $files.each(function() {
  43. if ('files' in this && this.files.length > 0) {
  44. // ToDo: Support Multiple on any input?
  45. // Just need a loop here..
  46. formData.append(this.name, this.files[0]);
  47. }
  48. });
  49. var $noFiles = $form.find(':not(input[type="file"])');
  50. $.each($noFiles.serializeArray(), function(i, pair) {
  51. formData.append(pair.name, pair.value);
  52. });
  53. options.data = formData;
  54. options.method = 'POST';
  55. options.contentType = false;
  56. options.processData = false;
  57. } else {
  58. options.data = $form.serializeArray();
  59. }
  60. $.ajax(options);
  61. };
  62. // 全局对象方法
  63. $.extend({
  64. Form : {
  65. ajaxSubmit : ajaxSubmit
  66. }
  67. });
  68. // 方法
  69. $.fn.extend({
  70. ajaxSubmit : function(callback) {
  71. $(document).off('submit',this.selector).on('submit',this.selector,function (e) {
  72. e.preventDefault();
  73. var $form = $(this);
  74. if ($form.attr('ajax-disabled') != undefined)
  75. return true;
  76. ajaxSubmit(this,callback);
  77. return false;
  78. });
  79. }
  80. });
  81. });