使用ajax上传图片(ajaxfileupload.js)

使用ajaxfileupload.js
页面中如此调用:
javascript:

function uploadImg(){
    $.ajaxFileUpload({
        url : 'uploadFile.action',secureuri : false,fileElementId : 'file',dataType : 'json',success : function(data,status) {

        },error : function(data,status,e) {
        alert(e);
        }
    });
}

html:

图片:<input type="file" name="file" id="file" class="required imgFile" size="30" />
<input type="button" value="上传" onclick="uploadImg();"/>

需要注意的是,ajaxfileupload.js已经好久没更新了,所以在新版jquery中需要对ajaxfileupload.js做如下更改:
新增两个方法(放到jQuery.extend里):

handleError: function (s,xhr,e) {
        if (s.error) {
            s.error.call(s.context || s,e);
        }
        if (s.global) {
            (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError",[xhr,s,e]);
        }
    },httpData: function (xhr,type,s) {
        var ct = xhr.getResponseHeader("content-type"),xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,data = xml ? xhr.responseXML : xhr.responseText;
        if (xml && data.documentElement.tagName == "parsererror")
            throw "parsererror";
        if (s && s.dataFilter)
            data = s.dataFilter(data,type);
        if (typeof data === "string") {
            if (type == "script")
                jQuery.globalEval(data);
            if (type == "json")
                data = window["eval"]("(" + data + ")");
        }
        return data;
    },

修改一个方法:

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();
            //alert($('param',data).each(function(){alert($(this).attr('value'));}));
        return data;
    }

本文引用了互联网上大量的资料,然后自我整理后完成,感谢大家。

相关文章

$.AJAX()方法中的PROCESSDATA参数 在使用jQuery的$.ajax()方...
form表单提交的几种方式 表单提交方式一:直接利用form表单提...
文章浏览阅读1.3k次。AJAX的无刷新机制使得在注册系统中对于...
文章浏览阅读1.2k次。 本文将解释如何使用AJAX和JSON分析器在...
文章浏览阅读2.2k次。/************************** 创建XML...
文章浏览阅读3.7k次。在ajax应用中,通常一个页面要同时发送...