这是一个jquery的扩展,用于无刷新的上传文件。
插件下载地址:
http://files.cnblogs.com/files/kissdodog/ajaxfileupload_JS_File.rar
具体的插件原理就不谈了,笔者在使用这个插件的途中遇到了一些问题,记录如下:
1.jQuery.handleError is not a function
这个函数是在jquery-1.4.2版本之前存在的,此后的版本中不存在这个函数
将这个函数复制到ajaxUploadFile文件末尾
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] );
}
},
2.一直是error,无法运行到success方法。
这个笔者有一点亲身体会是将调用插件时指定的数据类型的大小写和插件中的大小写保持一致。
即指定dataType:JSON
将插件中的if( type=”JOSN” ),同步保持大写,因为js是大小写区别的。
第二个是将
eval("data = " + data); // 会在data为字符串时抛出异常
改为
eval("data = \" "+data+" \" "); // 将data作为字符串
第三个是在数据格式为JSON时会走下面的程序走
if ( type == "JSON" )
{
// If you add mimetype in your response,
// you have to delete the '<pre></pre>' tag.
// The pre tag in Chrome has attribute, so have to use regex to remove
var data = r.responseText;
var rx = new RegExp("<pre.*?>(.*?)</pre>","i");
var am = rx.exec(data);
// this is the desired data extracted
// the only submatch or empty
var data = (am) ? am[1] : "";
eval( "data = " + data );
}
笔者经历发现eval()解析并没有问题,但是还报错。
经过排查发现是执行exec时报错,原因尚未找到,由于返回的内容确定没有<pre></pre>标签,所以直接将rx和am变量的两行代码注释掉。也就是:
if ( type == "JSON" )
{
// If you add mimetype in your response,
// you have to delete the '<pre></pre>' tag.
// The pre tag in Chrome has attribute, so have to use regex to remove
var data = r.responseText;
// var rx = new RegExp("<pre.*?>(.*?)</pre>","i");
// var am = rx.exec(data);
// this is the desired data extracted
// the only submatch or empty
// var data = (am) ? am[1] : "";
eval( "data = " + data );
}
发现程序返回成功。
ps:以后查找出原因再将报错原因附上。