最近做项目,需要上传表单元素中的文件POST到目标URL,并把得到的数据显示到本页面上,而不跳转到目标URL。那么,现在就要明确两件事:
1)不能直接提交表单,因为一旦点击submit就会自动跳转到action界面;
2)可以选择ajax进行异步数据传输;
原来只是用过ajax进行简单的数据传输,还没上传过文件呐,于是查了一下,如获至宝地发现了jQuery插件AjaxFileupload,专门用来上传文件~于是乎就马上踏上了AjaxFileupload的研究之旅。
一、实现步骤:
1)引入相关的js
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript" src="js/ajaxfileupload.js"></script>
2)代码编写
$.ajaxFileUpload({
url: "../GetInfo.jsp",//处理本文件的action
secureuri: false,
fileElementId: 'uploadFile1', //input type="file"的id
dataType: 'json',//定义数据的返回格式是json
success: function (data, status) {
console.log(data);
if(typeof(data.error) != 'undefined') {
if(data.error != '') {
alert(data.error);
} else {
alert(data.msg);
}
}
FillTable(data);
},
error: function (data, status, e) {
alert(e);
}
});
二、遇到的问题总结:
1)使用的AjaxFileupload版本与jQuery版本不相同导致报错
一开始使用的是jQuery-2.1.4版本,后来报错了,查了原因发现可能是版本不同,才发现AjaxFileupload的版本是1.2的(真是一个老古董),不过没办法,为了上传文件还是忍忍吧,就把jQuery版本换成了和它一样的老古董。然后问题解决~(AjaxFileupload版本与jQuery版本不用严格相同,但是也不能差太多)
2)AjaxFileupload文件上传成功但是不执行回调函数
修改ajaxfileupload.js源码,把最后几行代码中的代码
if ( type == "json" )
eval( "data = " + data );
修改成:
if ( type == "json" )
data=eval("("+data.replace("<pre>","").replace("</pre>","")+")");
3)控制台报错jQuery.handleError is not a function
现在大家至少也在用jquery1.9以上的版本,ajaxfileupload的版本早就不更新了,它例子里使用的Jquery是1.2的,好老呀。。。这个问题,我以前开发过程中遇过,网上说经测试(我是没测试),是版本1.4.2之后的版本才有handlerError方法,之前就不存在了,为了能够继续使用ajaxfileupload上传我们的附件,只好将代码拷进我们的项目中的ajaxfileupload.js文件中,如下:
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || s, xhr, status, e );
}
// Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
}
4)AjaxFileupload上传多文件的实现
修改ajaxfileupload.js源码,
//var oldElement = jQuery('#' + fileElementId);
//var newElement = jQuery(oldElement).clone();
//jQuery(oldElement).attr('id', fileId);
//jQuery(oldElement).before(newElement);
//jQuery(oldElement).appendTo(form);
//set attributes
for(var i in fileElementId)
{
var oldElement = jQuery('#' + fileElementId[i]);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
});
}