使用jquery.form.js的ajaxsubmit方法提交数据的Bug
周五同事遇到一个很奇怪的问题,调到下班,虽然问题解决了,但是不知道问题的具体原因,回来翻了翻代码,才发现症结所在,下面就分享出来,供遇到同样问题的同行们参考:
先把问题描述一下,做的功能是使用ajax向后台来提交数据,为了向用户进行很好的错误提示,后台中将出现错误时的错误原因返回给前端,前端使用jquery.form.js的ajaxsubmit来提交数据,并在success方法中提示“操作成功”,在error方法中提示错误原因。整个form提交的数据包括一些简单的input和一个文件的上传。下面是代码:
前端JSP代码:
- < form id ="wfAuditForm" method ="post" enctype ="multipart/form-data">
- < input type ="file" name ="posterUrlUploadPath" id ="posterUrlUploadPath" class ="fileUpload" title ="上传图片" />
< form id ="wfAuditForm" method ="post" enctype ="multipart/form-data">
< input type ="file" name ="posterUrlUploadPath" id ="posterUrlUploadPath" class ="fileUpload" title ="上传图片" />
前端JS代码:
- $("#wfAuditForm").ajaxSubmit({
- type: 'post',
- url: "data/resource/picture/save" ,
- success: function(data){
- alert( "success");
- $( "#wfAuditForm").resetForm();
- },
- error: function(XmlHttpRequest, textStatus, errorThrown){
- alert( "error");
- }
- });
$("#wfAuditForm").ajaxSubmit({
type: 'post',
url: "data/resource/picture/save" ,
success: function(data){
alert( "success");
$( "#wfAuditForm").resetForm();
},
error: function(XmlHttpRequest, textStatus, errorThrown){
alert( "error");
}
});
后台:
- public void save(HttpServletResponse response, HttpServletRequest request, Integer hasUpload,PictureResource pic) {
- response.setStatus(HttpServletResponse. SC_CONFLICT);
- }
public void save(HttpServletResponse response, HttpServletRequest request, Integer hasUpload,PictureResource pic) {
response.setStatus(HttpServletResponse. SC_CONFLICT);
}
问题是当提交的数据中file标签里面有值的话(有文件需要上传),即时后台返回的状态码不是200,也会触发js的success方法。
当然第一时间想到的是不是返回的状态码不是预期中的,于是使用了firebug对于通信进行了抓包,抓包后发现返回的的确是409(SC_CONFLICT),但是触发的还是success上面。后来意识到这种问题只有当有文件需要上传的时候才会发现,因此怀疑form提交的时候返回了两次response,一次是文件流从客户端到服务端的过程,一次是真正的数据提交的过程,因此使用了wireshark抓了几次包,抓出来的报文显示的确是只返回了一次response(当有文件上传的时候,会出现一个redirect的报文,这个在后面的博文中会有分析),这个说明跟http的网络通信及服务端处理没有关系。
问题到底出在什么地方呢?再次回过头来读jquery.form.js的代码,发现这段代码中有这么一段很可疑:
- var found = false;
- for ( var j=0; j < files.length; j++)
- if (files[j])
- found = true;
- if (options.iframe || found) // options.iframe allows user to force iframe mode
- fileUpload();
- else
- $.ajax(options);
var found = false;
for ( var j=0; j < files.length; j++)
if (files[j])
found = true;if (options.iframe || found) // options.iframe allows user to force iframe mode
fileUpload();
else
$.ajax(options);
这段代码的第一个for循环是遍历form中所有的file标签,一旦其中的一个file标签里面有值,就将found设置了true。后面的代码就是根据found来进行判断了,如果found为真(有需要上传的文件)将调用fileUpload方法,否则调用jquery的ajax方法。根据上面的现象描述,问题可能出现在fileUpload方法中。下面我们再看fileUpload方法:
- // private function for handling file uploads (hat tip to YAHOO!)
- function fileUpload() {
- var form = $form[0];
- var opts = $.extend({}, $.ajaxSettings, options);
- var id = 'jqFormIO' + $.fn.ajaxSubmit.counter++;
- var $io = $('<iframe id="' + id + '" name="' + id + '" />');
- var io = $io[0];
- var op8 = $.browser.opera && window.opera.version() < 9;
- if ($.browser.msie || op8) io.src = 'javascript:false;document.write("");';
- $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
- var xhr = { // mock object
- responseText: null,
- responseXML: null,
- status: 0,
- statusText: 'n/a',
- getAllResponseHeaders: function() {},
- getResponseHeader: function() {},
- setRequestHeader: function() {}
- };
- var g = opts.global;
- // trigger ajax global events so that activity/block indicators work like normal
- if (g && ! $.active++) $.event.trigger("ajaxStart");
- if (g) $.event.trigger("ajaxSend", [xhr, opts]);
- var cbInvoked = 0;
- var timedOut = 0;
- // take a breath so that pending repaints get some cpu time before the upload starts
- setTimeout(function() {
- $io.appendTo('body');
- // jQuery's event binding doesn't work for iframe events in IE
- io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
- // make sure form attrs are set
- var encAttr = form.encoding ? 'encoding' : 'enctype';
- var t = $form.attr('target');
- $form.attr({
- target: id,
- method: 'POST',
- encAttr: 'multipart/form-data',
- action: opts.url
- });
- // support timout
- if (opts.timeout)
- setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
- form.submit();
- $form.attr('target', t); // reset target
- }, 10);
- function cb() {
- if (cbInvoked++) return;
- io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
- var ok = true;
- try {
- if (timedOut) throw 'timeout';
- // extract the server response from the iframe
- var data, doc;
- doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
- xhr.responseText = doc.body ? doc.body.innerHTML : null;
- xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
- if (opts.dataType == 'json' || opts.dataType == 'script') {
- var ta = doc.getElementsByTagName('textarea')[0];
- data = ta ? ta.value : xhr.responseText;
- if (opts.dataType == 'json')
- eval("data = " + data);
- else
- $.globalEval(data);
- }
- else if (opts.dataType == 'xml') {
- data = xhr.responseXML;
- if (!data && xhr.responseText != null)
- data = toXml(xhr.responseText);
- }
- else {
- data = xhr.responseText;
- }
- }
- catch(e){
- ok = false;
- $.handleError(opts, xhr, 'error', e);
- }
- // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
- 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');
- // clean up
- setTimeout(function() {
- $io.remove();
- xhr.responseXML = null;
- }, 100);
- };
// private function for handling file uploads (hat tip to YAHOO!)
function fileUpload() {
var form = $form[0];
var opts = $.extend({}, $.ajaxSettings, options);var id = 'jqFormIO' + $.fn.ajaxSubmit.counter++;
var $io = $('<iframe id="' + id + '" name="' + id + '" />');
var io = $io[0];
var op8 = $.browser.opera && window.opera.version() < 9;
if ($.browser.msie || op8) io.src = 'javascript:false;document.write("");';
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); var xhr = { // mock object
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {}
}; var g = opts.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && ! $.active++) $.event.trigger("ajaxStart");
if (g) $.event.trigger("ajaxSend", [xhr, opts]); var cbInvoked = 0;
var timedOut = 0; // take a breath so that pending repaints get some cpu time before the upload starts
setTimeout(function() {
$io.appendTo('body');
// jQuery's event binding doesn't work for iframe events in IE
io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false); // make sure form attrs are set
var encAttr = form.encoding ? 'encoding' : 'enctype';
var t = $form.attr('target');
$form.attr({
target: id,
method: 'POST',
encAttr: 'multipart/form-data',
action: opts.url
}); // support timout
if (opts.timeout)
setTimeout(function() { timedOut = true; cb(); }, opts.timeout); form.submit();
$form.attr('target', t); // reset target
}, 10); function cb() {
if (cbInvoked++) return; io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false); var ok = true;
try {
if (timedOut) throw 'timeout';
// extract the server response from the iframe
var data, doc;
doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
xhr.responseText = doc.body ? doc.body.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (opts.dataType == 'json' || opts.dataType == 'script') {
var ta = doc.getElementsByTagName('textarea')[0];
data = ta ? ta.value : xhr.responseText;
if (opts.dataType == 'json')
eval("data = " + data);
else
$.globalEval(data);
}
else if (opts.dataType == 'xml') {
data = xhr.responseXML;
if (!data && xhr.responseText != null)
data = toXml(xhr.responseText);
}
else {
data = xhr.responseText;
}
}
catch(e){
ok = false;
$.handleError(opts, xhr, 'error', e);
} // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
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'); // clean up
setTimeout(function() {
$io.remove();
xhr.responseXML = null;
}, 100);
};</pre>
很明显,这是通过使用隐藏iframe来模拟ajax实现的文件上传(参见该方法的介绍博文《谈谈使用iFrame模拟Ajax的问题》
)。注意在方法cb中有这么一段代码:
- catch(e){
- ok = false;
- $.handleError(opts, xhr, 'error', e);
- }
- // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
- if (ok) {
- opts.success(data, 'success');
- if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
- }
catch(e){
ok = false;
$.handleError(opts, xhr, 'error', e);
}// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (ok) {
opts.success(data, 'success');
if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
}</pre>
从这个代码中可以看出,仅仅是当出现异常的时候(关于js异常的情况,请参见介绍博文《Javascript的异常处理介绍》
),才会触发我们设定的error方法,其余情况都会触发success,也就是说即时http返回的不是200,而是其他的错误码,只要不出现异常就不会触发error方法!找到问题原因了,我们怎么来实现根据http返回的状态码来进行相应的处理呢?一种策略是将状态码写到返回的是text的文本中,然后在客户端根据文本进行判断。或许另外一种方法是重写这个cb方法,在其中根据http的状态码来进行不同的处理,不过我还没有找到获取返回的状态码的方法。
互联网码农一枚,欢迎微博互粉,进行交流:http://weibo.com/icemanhit
使用jquery.form.js的ajaxsubmit方法提交数据的Bug的更多相关文章
- jquery.form.js 让表单提交更优雅
jquery.form.js 让表单提交更优雅.可以页面不刷新提交表单,比jQuery的ajax提交要功能强大. 1.引入 <script src="/src/jquery-1.9.1 ...
- jQuery通过jquery.form.js插件使用AJAX提交Form表单
我简单使用了一下,jQuery Form插件有一下优点: 1.支持提交前验证. 2.支持提交后回调. 3.采用AJAX方式,有很好的用户体验 4.提交方式是灵活.只要指定要提交的form ID即可. ...
- [转]jquery.form.js的ajaxSubmit和ajaxForm使用
参考 http://www.cnblogs.com/popzhou/p/4338040.html 依赖的脚本文件 <script src="../Javascript/jquery-1 ...
- 【Jquery+Express.js】 submit() 方法提交form
前端页面 .html 生成一个动态模块 Modal <div class="modal fade" id="addStaff" tabindex=&quo ...
- 使用Jquery.form.js ajax表单提交插件弹出下载提示框
现象: 使用jquery的from做ajax表单提交的时候,后台处理完毕返回json字符串,此时浏览器提示下载一个json文件而不是在success里面继续解析该json对象. 具体的原因: 浏览器兼 ...
- 文件上传功能 -- jquery.form.js/springmvc
距离上一篇 文件上传下载样式 -- bootstrap(http://www.cnblogs.com/thomascui/p/5370947.html)已经三周时间了,期间一直考虑怎么样给大家提交一篇 ...
- input ,button, textarea 1)使用disabled , 2) 显示值, 3) 表单提交. 4) jquery.form.js ajaxSubmit() 无刷新ajax提交表单.
1.使用disabled input , button textarea 可以 被 禁用, 禁用的效果 : 1) 上面的点击事件无法使用 --- button : 下面的 onclick ...
- jquery.form.js的重置表单增加hidden重置代码
jquery.form.js的resetForm()方法无法重置hidden元素,打开文件在1460行加上以下代码即可
- jquery.form.js实现将form提交转为ajax方式提交的使用方法
本文实例讲述了jquery.form.js实现将form提交转为ajax方式提交的方法.分享给大家供大家参考.具体分析如下: 这个框架集合form提交.验证.上传的功能. 这个框架必须和jquery完 ...
随机推荐
- 2018-8-10-win10-uwp-禁止编译器优化代码
title author date CreateTime categories win10 uwp 禁止编译器优化代码 lindexi 2018-08-10 19:16:50 +0800 2018-2 ...
- 洛谷P1080 [NOIP2012提高组D1T2]国王游戏 [2017年5月计划 清北学堂51精英班Day1]
P1080 国王游戏 题目描述 恰逢 H 国国庆,国王邀请 n 位大臣来玩一个有奖游戏.首先,他让每个大臣在左.右 手上面分别写下一个整数,国王自己也在左.右手上各写一个整数.然后,让这 n 位大臣排 ...
- 让Drewtech的J2534 ToolBox 软件支持任何J2534的设备
更改windows注册表中的FunctionLibrary和ConfigApplication,将DLL和exe路径替换原来的,其他不要动. 或者 create second key in regis ...
- 洛谷 2055 [ZJOI2009]假期的宿舍——二分图匹配
题目:https://www.luogu.org/problemnew/show/P2055 #include<iostream> #include<cstdio> #incl ...
- 缺氧debug模式开启及功能
在游戏OxygenNotIncluded_Data文件夹创建一个debug_enable.txt的空文本文档 在缺氧目录下添加debug_enable.txt文件 按删除键就可以开启debug模式 需 ...
- 使用dos行命令实现文件夹内文件名统计
1.进入在dos环境下 2.进入需要统计的目录下. 3.使用命令 dir /b>e:1.xls 结果:会在路径(e:\资料\资料整理)下生成一个新的文件(1.xls).1.xls把路径(e:\资 ...
- Cross-site scripting(XSS)
https://en.wikipedia.org/wiki/Cross-site_scripting Definition Cross-site scripting (XSS) is a type o ...
- ecshop二次开发之百度地图
案例效果展示: 代码实现: 1.在ecshop后台找到文章管理->文章分类->添加文章分类,添加一个顶级分类,叫做"合作单位",并且让其显示在导航栏.如下图: 1.在e ...
- Ajax中post方法400和404的问题
1.从400变成404 我相信有很多人都用过Ajax技术来获取数据,一般都是使用get来获取的,但是敏感信息就不能继续用get了,于是就换成了post,但是用post的时候有时候发生一些奇怪的事情,比 ...
- 去掉goland中间的令人烦躁的竖线
去掉“configured in code Style options”前面的勾即可.