使用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-2-13-C#-相对路径转绝对路径
title author date CreateTime categories C# 相对路径转绝对路径 lindexi 2018-2-13 17:23:3 +0800 2018-2-13 17:23 ...
- (转载) poj1236 - Network of Schools
看到一篇挺好的代码,适合初学者,转载自 博主 wangjian8006 原地址:http://blog.csdn.net/wangjian8006/article/details/7888558 题目 ...
- Leetcode34.Find First and Last Position of Element in Sorted Array在排序数组中查找元素的位置
给定一个按照升序排列的整数数组 nums,和一个目标值 target.找出给定目标值在数组中的开始位置和结束位置. 你的算法时间复杂度必须是 O(log n) 级别. 如果数组中不存在目标值,返回 [ ...
- Vue表单验证插件的制作过程
一.表单验证模块的构成 任何表单验证模块都是由 配置――校验――报错――取值 这几部分构成的. 配置: 配置规则 和配置报错,以及优先级 校验: 有在 change 事件校验, 在点击提交按钮的时候校 ...
- VisualTreeHelper使用——使用BFS实现高效率的视觉对象搜索
BFS,即广度优先搜索,是一种典型的图论算法.BFS算法与DFS(深度优先搜索)算法相对应,都是寻找图论中寻路的常用算法,两者的实现各有优点. 其中DFS算法常用递归实现,也就是常见的一条路找到黑再找 ...
- 在n个球中,任意取出m个(不放回),求共有多少种取法
要求: 在n个球中,任意取出m个(不放回),求共有多少种取法 分析: 假设3个球A,B,C,任意取出2个,可分为取出的球中含A的部分和不含A的部分.即AB,AC为一组,BC为一组. 设函数F(n,m) ...
- 【水滴石穿】ReactNativeDemo
这个博主他的功底算是特别棒的了,能够把一些基础的例子,通过精巧的方式布局在一个小的demo里面 很值得我学习 放上博主的链接:https://github.com/jianiuqi/ReactNati ...
- php实现图片以base64显示的方法达到效果
目前Data URI scheme支持的类型有: data:text/plain,文本数据data:text/html,HTML代码data:text/html;base64,base64编码的HTM ...
- uml设计之多重性
---------------------------------------------------------------------------------------------------- ...
- JasperStudio study..
https://blog.csdn.net/shiyun123zw/article/details/79166448