使用ajaxfileupload实现文件异步上传

本文详细介绍了使用Ajax进行文件上传时遇到的错误,包括jQuery版本问题和JSON数据结构不匹配导致的问题,并提供了解决方案。重点讨论了如何解决错误进入error而非success的情况,以及如何正确处理JSON返回数据。
function ajaxFileUpload() {
//    var callback = function(result) {
//        var jsonObj = {};
//        jsonObj.Rows = result.resourceList;
//        resouceGrid.set({ data: jsonObj });
//    };
//    var para = {nodeId:$("#nodeId").val(),};
//    $.post($('#initPath').val() + '/ResourceController.do?method=imgUpload', para, callback);


    $.ajaxFileUpload
(
{
url: $('#initPath').val() + '/ResourceController.do?method=imgUpload&nodeId=' + $("#nodeId").val(),
secureuri:false,
fileElementId:'imgFile',
dataType: 'text',
success: function (data, status)
{
                    debugger;
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
},
error: function (data, status, e)
{
                    debugger;
alert(e);
}
}
);
return false;

}


==================


ajaxfileupload 异步上传图片返回无法进入error,控制台打印报错如下:

Uncaught TypeError: Object function (a,b){return new e.fn.init(a,b,h)} has no method 'handleError'

主要是jquery版本的问题,需要更高的jquery版本

后来通过想ajaxfileupload.js加入如下代码解决

Js代码 复制代码 收藏代码
  1. handleError: function( s, xhr, status, e ) {
  2. // If a local callback was specified, fire it
  3. if ( s.error ) {
  4. s.error.call( s.context || window, xhr, status, e );
  5. }
  6. // Fire the global callback
  7. if ( s.global ) {
  8. (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
  9. }
  10. },
handleError: function( s, xhr, status, e ) {
    // If a local callback was specified, fire it
    if ( s.error ) {
        s.error.call( s.context || window, xhr, status, e );
    }
    // Fire the global callback
    if ( s.global ) {
        (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
    }
}, 

如果无法进入success,看看是否是dataType 的类型返回不匹配

我遇到的情况是dataType='json';

后台返回数据代码如下:

Java代码 复制代码 收藏代码
  1. Gson gson = new Gson();
  2. Map map = new HashMap();
  3. map.put("photoId", photo.getPhotoId());
  4. map.put("photopath", TargetCommentsPhotopathHelper.getPhotopath_x200(photo.getPath()));
  5. String gsonStr = gson.toJson(map);
  6. PrintWriter out = response.getWriter();
  7. out.print(gsonStr);
Gson gson = new Gson();

Map map = new HashMap();
            map.put("photoId", photo.getPhotoId());
            map.put("photopath", TargetCommentsPhotopathHelper.getPhotopath_x200(photo.getPath()));
            
            String gsonStr = gson.toJson(map);
            PrintWriter out = response.getWriter();
            out.print(gsonStr);

这样js会进error,不进success,主要是json返回的数据结构不对,可以让返回正确结构或修改dataType='text';再自行解析


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值