ajaxSubmit提交檔案表單不執行success
阿新 • • 發佈:2019-02-11
先描述一下我遇到的問題,系統裡所有的表單都用ajaxSubmit來提交,成功回撥success函式,普通表單都是沒有問題的,但是有檔案上傳的表單就不行了,不會回撥success,經驗證會回撥complete,然後就除錯
發現有一個錯誤undefined is not a function 找到程式碼是這樣的
var $io = $('<iframe id="' + id + '" name="' + id + '" src="' + opts.iframeSrc + '" onload="(jQuery(this).data(\'form-plugin-onload\'))()" />');
外掛自己建立個iframe onload裡面報錯,該了一下改成onload="(function(){....})()"。
很明顯這樣雖然沒有報錯了,但是這不是沒有呼叫success方法的原因,繼續看看原始碼發現有個timeout引數,如果timeout有值的話就會反覆執行一個方法,出發success的地方就在這裡
if (opts.timeout)
setTimeout(function() {
timedOut = true;
cb();
}, opts.timeout);
function cb() { if (cbInvoked) return; var ok = true; try { if (timedOut) throw 'timeout'; var data, doc; doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document; var isXml = opts.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml=' + isXml); if (!isXml && (doc.body == null || doc.body.innerHTML == '')) { if (--domCheckCount) { log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } log('Could not access iframe DOM after 100 tries.'); return; } log('response detected'); cbInvoked = true; xhr.responseText = doc.body ? doc.body.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; xhr.getResponseHeader = function(header) { var headers = { 'content-type' : opts.dataType }; return headers[header]; }; if (opts.dataType == 'json' || opts.dataType == 'script') { var ta = doc.getElementsByTagName('textarea')[0]; if (ta) xhr.responseText = ta.value; else { var pre = doc.getElementsByTagName('pre')[0]; if (pre) xhr.responseText = pre.innerHTML; } } else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) { xhr.responseXML = toXml(xhr.responseText); } data = $.httpData(xhr, opts.dataType); } catch (e) { log('error caught:', e); ok = false; xhr.error = e; $.handleError(opts, xhr, 'error', e); } if (ok) { opts.success(data, 'success'); if (g) $.event.trigger("ajaxSuccess", [ xhr, opts ]); } if (g) $.event.trigger("ajaxComplete", [ xhr, opts ]); if (g && !--$.active) $.event.trigger("ajaxStop"); if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error'); setTimeout(function() { $io.removeData('form-plugin-onload'); $io.remove(); xhr.responseXML = null; }, 100); }
這麼長的函式我沒仔細看完的,然後設定了一下timeout引數
結果不行,報了個timeout異常,看看程式碼,發現在setTimeout的時候有一句timeOut=true,然後才執行cb()的,而cb剛開始try就有一個if(timeOut) throw "timeout",我不知到作者是什麼意圖,我動手改了
又碰到一個問題,$.httpData is not a function,try裡面的最後一句
data = $.httpData(xhr, opts.dataType);
可能是想把結果轉換成dataType指定的型別,不過我沒有找到$.httpData的定義,也許外掛還有其他附帶的js,因為我用的都是返回json所以自己統一當作json處理,終於達到目的了。
其實本人js不是很精通,只是這樣做達到自己目的了,但是在網路上似乎沒找到誰遇到和我一樣的問題,如果有發現真實原因還請告知啊。
2014.11.03補充
其實後來再用jquery.form都沒有這個問題了,可能是版本問題也可能是瀏覽器問題