jquery 簡易外掛 非同步form提交、檔案非同步提交,jquery 檔案非同步提交
阿新 • • 發佈:2018-11-19
$.ajax 預設不支援檔案提交,
這裡提供一個form target = iframe 的非同步提交外掛
如果需要提交檔案form 需要設定屬性 enctype="multipart/form-data",使用外掛後會自動使用target = iframe提交form
實現非同步提交,相容性好,用法簡單!
(function ($){ /** * @name from的iframe提交 v0.1 * @desc 主要是考慮帶file的from非同步提交 * @param options * success 成功呼叫函式 success(retex,toiframe); * error 失敗呼叫函式 error(toiframe); * complete 完成呼叫函式 complete(toiframe,'success'); * isSubmit 是否自動提交,預設 false * isOne 是否一次性, 預設 false * @pending isAddDiscern 是否增加請求標識(預設iframe_async=1)如果是字串新增此引數請求值為1 * @example $('form#file').form_iframe({success:function (retex){alert('提交成功,'+retex)}}); * @author hank */ $.fn.form_iframe = function (options){ var my = $(this); var defaults = $.extend({}, $.fn.form_iframe.defaults); var opts = $.extend(defaults, options); my.each(function (){ var target, iframe_name, toiframe, myform = $(this); if(!myform.is('form')) return true; do{ iframe_name = 'iframe_'+((Math.random()*10000000000000000).toString()).slice(0,14); }while($('iframe[name="'+iframe_name+'"]').size() > 0); toiframe = $('<iframe form_iframe="1" name="'+iframe_name+'"></iframe>').hide(); myform.attr('target',iframe_name); myform.after(toiframe); myform.bind('submit',function (){ var subCou = (isNaN(parseInt($(this).attr('form_iframe-cou'))) ? 1 : (parseInt($(this).attr('form_iframe-cou'))+1)); $(this).attr('form_iframe-cou', subCou); toiframe.attr('form_iframe-cou', subCou); }); toiframe.data('myform',myform); toiframe.bind({"error.form_iframe":function (){ if(!toiframe.is('[form_iframe-cou]')){ return; } opts.error(toiframe); opts.complete(toiframe,'failure'); _my_complete(toiframe, 'failure'); }, "load.form_iframe":function (){ if(!toiframe.is('[form_iframe-cou]')){ return; } var retdom = $(this).contents(), retex = $(retdom).text(); opts.success(retex,toiframe); opts.complete(toiframe,'success', retex); _my_complete(toiframe, 'success'); }}); if(opts.isSubmit) myform.submit(); }); function _my_complete(iframe){ if(opts.isOne) iframe.remove(); } return my; }; $.fn.form_iframe.defaults = { success: function (){}, error: function (){}, complete:function (){}, isSubmit:false, isOne:false }; })(jQuery);