今天用ajaxfileupload.js上传文件时,用到了一个让人很郁闷的事情,就是无论上传文件成功与否,总是调用error回调函数,一直不用心success函数。
代码如下:
//上传文件
$("#CompChange").click(function() {
var params = $("#CompchangeTable").serialize();
var json0={'video.slogan':$('#Cbasic_score').val(),'video.videoKind':$("#Cextra_score").val(),
'video.videoName':$("#name").val()};
$.ajaxFileUpload({
type: "POST",
url: "adminAction-upFile.action",
data:json0,//要传到后台的参数,没有可以不写
secureuri : false,//是否启用安全提交,默认为false
fileElementId:['file1','file2'],//文件选择框的id属性
dataType: 'json',//服务器返回的格式
async : false,
success: function(data){
alert("成功");
},
error: function (data, status, e){
alert("失败");
}
});
});
上传后会报错:
从报错上看可能是多了一个"<"符号。经过大量的尝试后,终于发现了不对劲的地方。我是把dataType的类型换成了context类型,并在success函数中打印出data。
结果是:
你回发现返回的数据中有<pre>标签,问题终于找到了,原来是JSon格式,但是返回的格式明显不是JSon格式,在网上查了一下才知道有时候后台必须要则么做,所以只能找别的方法了,最后就在ajaxfileupload.js文件里发现了这个:
uploadHttpData : function(r, type) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if (type == "script")
jQuery.globalEval(data);
// Get the JavaScript object, if JSON is used.
if (type == "json"){
eval("data = " + data);
}
// evaluate scripts within html
if (type == "html")
jQuery("<div>").html(data).evalScripts();
return data;
}
这就返回的值,返回JSon格式时,它直接把数据赋值,这肯定是不行的,所以我们要做修改:
uploadHttpData : function(r, type) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if (type == "script")
jQuery.globalEval(data);
// Get the JavaScript object, if JSON is used.
if (type == "json"){
以下为新增代码///
data = r.responseText;
var start = data.indexOf(">");
if(start != -1) {
var end = data.indexOf("<", start + 1);
if(end != -1) {
data = data.substring(start + 1, end);
}
}
///以上为新增代码///
eval("data = " + data);
}
// evaluate scripts within html
if (type == "html")
jQuery("<div>").html(data).evalScripts();
return data;
}
我们把中间的截取出来就行了。
这就是我的解决方法,希望对其他人也有用。