struts2和ajaxfileupload.js和jquery.form.min.js实现异步上传图片功能(浏览器兼容)-maojw

吴炎彬
2023-12-01

一 . 前言
     ajaxfileupload.js这个插件已经不进行更新了,所以此方法慎用慎用慎用慎用慎用,容易入坑啊!!!
     实现:
             base64图片回显;
             图片上传后台进行图片ocr识别,识别图片上的数据与前端数据对比不一致的,红色高亮显示;       
             图片使用二进制流保存数据库;
     功能:
         异步上传图片,此插件可以实现对上传文件后缀名和上传文件大小进行限制;
     注意:
         jquery版本应在1.9以下使用.本次使用的案例为jquery.form.min.js;

二 . 步骤
     
<1>导入ajaxfileupload.js和jquery.form.min.js文件
    

     <script src="${pageContext.request.contextPath}/js/jquery.form.min.js" type="text/javascript"></script>
     <script src="${pageContext.request.contextPath}/js/ajaxfileupload.js" type="text/javascript"></script>  

 <2> 调用ajaxFileUpload方法

<script type="text/javascript">
//上传图片的方法,
function ajaxFileUpload(imgObj,count){
     //上传图片成功后检验图片的宽和高
    checkWidthHeight(imgObj,count);
    var no=$('#no').attr("value");
    var name=$('#name').attr("value");
   
//调用ajaxfileupload.js中的方法
$.ajaxFileUpload({
    url:'${pageContext.request.contextPath}/user-json/upload.do',//上传图片要提交到的action
    async:false,//属性设置就是同步方式(默认情况下,为true)
    secureuri:false,//是否用安全提交,默认为false
    fileElementId:['imgF','imgB'],//file选择文件的框的id(原始的是一个,修改成了两个id)
    fileFilter:["jpg","jpeg","bmp","png"],//文件过滤后缀,只支持此[]中的后缀的文件
    fileSize:5,//文件限制大小,最大为5M
    data:{//上传的参数,也可以不上传
        "no":no,
        "name":name,
        "count":count},
        count:count,
        dataType:'json',//数据返回格式,如果用json,需要修改ajaxfileupload.js中的内容
    success: function (data,status){
        //获得json格式数据的值,并转换显示图片在页面上
        if(status == "success"){
              //ajax执行成功后,对返回的数据进行处理
            ocrResData(data);
        }else{
            alert("上传图片失败,请重新尝试!");
        }
    }
});
if(count==1){
     //字体提示3000毫秒后自动消失
    $('.alertF').html('正在ocr识别,请耐心等待,若无响应,请重新尝试下...').show().delay(3000).fadeOut();
}
if(count ==2){
    //字体提示3000毫秒后自动消失
    $('.alertB').html('正在ocr识别,请耐心等待,若无响应,请重新尝试下...').show().delay(3000).fadeOut();
}
}


//ocr识别完成后,对返回的数据进行判断处理
function ocrResData(data){
    var user = data.User;
    var nameRes = user.name;
    var noRes = user.no;
    if(null != data.frontImg && "" != data.frontImg){
          //使用base64回显图片时,image/*方式不可行(ie浏览器不能识别*通配符),所以此处进行了强控制image/jpg
        $('#frontImg').attr("src","data:image/jpg;base64,"+data.frontImg);
    }
    if(null != data.backImg && "" != data.backImg) {
       //使用base64回显图片时,image/*方式不可行(ie浏览器不能识别*通配符),所以此处进行了强控制image/jpg
        $('#backImg').attr("src","data:image/jpg;base64,"+data.backImg);
    }
     //ocr识别后的图片数据与前端数据对比不一致的,进行红色高亮显示
    if(null != nameRes && nameRes != getValue("name")){
        addColor("name",nameRes);
    }
    if(null != noRes && noRes != getValue("no")){
        addColor("no",noRes);
    }   
}
function addColor(id,idRes){
    $('#'+id+'').val(idRes).attr("style","color: red");
}
function getValue(id){
    return $('#'+id+'').attr("value");
}
//校验图片的宽和高(执行完后台程序,执行该操作)
function checkWidthHeight(imgObj,count){
    var _URL = window.URL || window.webkitURL;
    var file, img;
    if ((file = imgObj.files[0])) {
        img = new Image();
        img.onload = function () {
        if(this.width <= 8 || this.width > 4000 || this.height <= 8 || this.height > 4000 ){
            alert("身份证照片,宽和高必须大于 8px,小于等于 4000px");
        if(count ==1 ){
            $('#imgF').val("");
        }
        if(count ==2 ){
            $('#imgB').val("");
        }
        return;
        }
    };
    img.src = _URL.createObjectURL(file);
}
}
</script>


    <3> form表单中的enctype="multipart/form-data"

 

<form id="editForm" action="${pageContext.request.contextPath}/user/edit.do" method="post" validate="true" enctype="multipart/form-data" onsubmit="return validate()">
<s:token />
*****
<tr>
    <td>正面照</td>
    <td>
        <input type="file" name="imgF" id="imgF" accept="image/*" onchange="ajaxFileUpload(this,'1');" />
        <img id="frontImg" src = "data:image/jpg;base64,${frontImg}" width='250' height='200'/>
    <span/>
    <p id = "frontReminder" style="display: block;color: #999999">ocr识别后,请确认是否正确..</p>
    <div class="alertF" style="color: red"></div>
</td>
</tr>
<tr>
    <td>反面照</td>
    <td>
         <input type="file" name="imgB" id="imgB" accept="image/*" onchange="ajaxFileUpload(this,'2');"/>
         <!-- 此img用于本地数据库中的图片回显;此处image/jpg(不能写成image/*,因为ie不识别*通配符,所以会导致回显失败) -->
         <img id="backImg" src = "data:image/jpg;base64,${backImg}" width='250' height='200'/>
        <span/>
        <p id = "backReminder" style="display: block;color: #999999">ocr识别后,请确认是否正确..</p>
        <div class="alertB" style="color: red"></div>
    </td>
</tr>

    
     <4>Olp-Struts.xml中的配置
          <!-- 建议同一个功能如果有ajax异步的方法,建议重新单独写一个package-->

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>  
         <package name="package-user" namespace="/user" extends="default">
        <!--查询 -->
        <action name="list" class="UserAction" method="list">
            <result name="success">/user/userlist.jsp</result>
        </action>
         </package>

        <package name="package-user-json" namespace="/user-json" extends="default-json">
        <action name="upload" class="UserAction" method="upload">
        <result name="success" type="json">
            <!-- 该参数解决ie浏览器兼容问题(返回的json串,ie会提示下载json.upload文件) -->
            <param name="contentType">text/html</param>
        </result>
        <result name="error" type="json">
             <!-- 该参数解决ie浏览器兼容问题 -->
            <param name="contentType">text/html</param>
        </result>
        </action>
        </package>
 </struts> 


     <5>UserAction中的配置

 

public class UserAction{
    //需要和前端的保持一致imgF
    private File imgF;
    private String imgFContentType;
    private String imgFFileName;


     //需要和前端的保持一致imgB
    private File imgB;
    private String imgBContentType;
    private String imgBFileName;


    ****************


}

     <6>ajaxfileupload.js中的修改
****************************************************

 

jQuery.extend({
    createUploadIframe: function(id, uri){
        //create frame
        var frameId = 'jUploadFrame' + id;
        if(window.ActiveXObject) {
          //修改后的代码(可以兼容浏览器的版本)jQuery.browser.version 方法在jquery高版本中去掉了
            if (jQuery.browser.version == "9.0" || jQuery.browser.version == "10.0") {
                var io = document.createElement('iframe');
                io.id = frameId;
                io.name = frameId;
            } else if (jQuery.browser.version == "6.0" || jQuery.browser.version == "7.0" || jQuery.browser.version == "8.0") {
                var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
            if (typeof uri == 'boolean') {
                io.src = 'javascript:false';
            } else if (typeof uri == 'string') {
                io.src = uri;
            }
            }
        } else {
            var io = document.createElement('iframe');
            io.id = frameId;
            io.name = frameId;
        }
    io.style.position = 'absolute';
    io.style.top = '-1000px';
    io.style.left = '-1000px';
    document.body.appendChild(io);
    return io;
},
createUploadForm: function(id, fileElementId){
    //create form
    var formId = 'jUploadForm' + id;
    var fileId = 'jUploadFile' + id;
    var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"> </form>');
      //源代码:只支持一个fileElementId的校验
     // var oldElement = $('#' + fileElementId);
     // var newElement = $(oldElement).clone();
     // $(oldElement).attr('id', fileId);
     // $(oldElement).before(newElement);
     // $(oldElement).appendTo(form);


    //修改后的代码:可以上传多个fileElementId
    if(typeof(fileElementId) == 'string'){
        fileElementId = [fileElementId];
    }
    for(var i in fileElementId){
        var oldElement = $('#' + fileElementId[i]);
        var newElement = $(oldElement).clone(true);
        $(oldElement).attr('id', fileId);
        $(oldElement).before(newElement);
        $(oldElement).appendTo(form);
    }
    //set attributes
    $(form).css('position', 'absolute');
    $(form).css('top', '-1200px');
    $(form).css('left', '-1200px');
    $(form).appendTo('body');
    return form;
},
addOtherRequestsToForm: function(form,data){
    // add extra parameter
    var originalElement = $('<input type="hidden" name="" value="">');
    for (var key in data) {
        name = key;
        value = data[key];
        var cloneElement = originalElement.clone();
        cloneElement.attr({'name':name,'value':value});
        $(cloneElement).appendTo(form);
    }
    return form;
},


ajaxFileUpload: function(s) {
    // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
     //原来的代码
    // s = jQuery.extend({}, jQuery.ajaxSettings, s);


    //修改后的代码:可以校验上传图片的后缀(fileFilter),图片的大小(fileSize),count为了区别是哪张图片
    s = jQuery.extend({fileFilter:"",fileSize:0,count:""}, jQuery.ajaxSettings, s);
    if(s.count == "1"){
        var fileElementIdCount = $('#' + s.fileElementId[0]);
    }else if(s.count == "2"){
        var fileElementIdCount = $('#' + s.fileElementId[1]);
    }
    var fileName = fileElementIdCount.val();
    console.log($('#' + s.fileElementId));
    if(fileName == undefined || fileName == null || fileName == ""){
        return;
    }
    var extention = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    if (s.fileFilter && s.fileFilter.indexOf(extention) < 0) {
        alert("不支持 " + extention + " 为后缀名的文件!");
        fileElementIdCount.val("");
        return;
    }
    //文件大小限制
    if (s.fileSize > 0) {
        var fs = 0;
        try {
            if (window.ActiveXObject) {
                //IE浏览器
                var image = new Image();
                image.dynsrc = fileName;
                fs = image.fileSize;
            } else {
                fs = fileElementIdCount[0].files[0].size;
            }
         } catch(e) {
            }
        if (fs > s.fileSize*1024*1024) {
            fs = fs/1024/1024;
            fs = fs.toString().substring(0,4);
            alert("当前文件大小 " + fs + "MB 超过允许的限制值 " + s.fileSize +"MB!");
            fileElementIdCount.val("");
            return;
        }
}
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId);
if ( s.data ) form = jQuery.addOtherRequestsToForm(form,s.data);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow){
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;

}else if(io.contentDocument){
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e){
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );


// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
$(io).remove();
$(form).remove();
} catch(e){
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
// var io = $('#' + frameId);
var form = $('#' + formId);
$(form).attr('action', s.url);
$(form).attr('method', 'POST');
$(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
$(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
return {abort: function () {}};
},

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" ){
        // 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
         // var data = (am) ? am[1] : ""; //the only submatch or empty
         // eval( "data = " + data );
         // data = jQuery.parseJSON(jQuery(data).text());
        //原始代码******
        // 修改第一版*****:文件上传的话返回的json字符串会带有<pre>开头的一串字符
         // data = data;
        // 修改第一版*****
         // replace替换,是因为返回的数据是以<pre >...</pre>包裹的数据
        data = data.replace("</pre>","");
        data = data.replace(/<pre[\w\W]*>/,"");
        data = eval("("+data+")");
}
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
},
handleErrorExt: 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]);
}
},
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] );
}
}
})

     <7>jquery.form.min.js

!
function(a) {
	"function" == typeof define && define.amd ? define(["jquery"], a) : "object" == typeof module && module.exports ? module.exports = function(b, c) {
		return void 0 === c && (c = "undefined" != typeof window ? require("jquery") : require("jquery")(b)),
		a(c),
		c
	}: a(jQuery)
} (function(a) {
	"use strict";
	function b(b) {
		var c = b.data;
		b.isDefaultPrevented() || (b.preventDefault(), a(b.target).closest("form").ajaxSubmit(c))
	}
	function c(b) {
		var c = b.target,
		d = a(c);
		if (!d.is("[type=submit],[type=image]")) {
			var e = d.closest("[type=submit]");
			if (0 === e.length) return;
			c = e[0]
		}
		var f = c.form;
		if (f.clk = c, "image" === c.type) if (void 0 !== b.offsetX) f.clk_x = b.offsetX,
		f.clk_y = b.offsetY;
		else if ("function" == typeof a.fn.offset) {
			var g = d.offset();
			f.clk_x = b.pageX - g.left,
			f.clk_y = b.pageY - g.top
		} else f.clk_x = b.pageX - c.offsetLeft,
		f.clk_y = b.pageY - c.offsetTop;
		setTimeout(function() {
			f.clk = f.clk_x = f.clk_y = null
		},
		100)
	}
	function d() {
		if (a.fn.ajaxSubmit.debug) {
			var b = "[jquery.form] " + Array.prototype.join.call(arguments, "");
			window.console && window.console.log ? window.console.log(b) : window.opera && window.opera.postError && window.opera.postError(b)
		}
	}
	var e = {};
	e.fileapi = void 0 !== a('<input type="file">').get(0).files,
	e.formdata = void 0 !== window.FormData;
	var f = !!a.fn.prop;
	a.fn.attr2 = function() {
		if (!f) return this.attr.apply(this, arguments);
		var a = this.prop.apply(this, arguments);
		return a && a.jquery || "string" == typeof a ? a: this.attr.apply(this, arguments)
	},
	a.fn.ajaxSubmit = function(b, c, g, h) {
		function i(c) {
			var d, e, f = a.param(c, b.traditional).split("&"),
			g = f.length,
			h = [];
			for (d = 0; d < g; d++) f[d] = f[d].replace(/\+/g, " "),
			e = f[d].split("="),
			h.push([decodeURIComponent(e[0]), decodeURIComponent(e[1])]);
			return h
		}
		function j(c) {
			for (var d = new FormData,
			e = 0; e < c.length; e++) d.append(c[e].name, c[e].value);
			if (b.extraData) {
				var f = i(b.extraData);
				for (e = 0; e < f.length; e++) f[e] && d.append(f[e][0], f[e][1])
			}
			b.data = null;
			var g = a.extend(!0, {},
			a.ajaxSettings, b, {
				contentType: !1,
				processData: !1,
				cache: !1,
				type: l || "POST"
			});
			b.uploadProgress && (g.xhr = function() {
				var c = a.ajaxSettings.xhr();
				return c.upload && c.upload.addEventListener("progress",
				function(a) {
					var c = 0,
					d = a.loaded || a.position,
					e = a.total;
					a.lengthComputable && (c = Math.ceil(d / e * 100)),
					b.uploadProgress(a, d, e, c)
				},
				!1),
				c
			}),
			g.data = null;
			var h = g.beforeSend;
			return g.beforeSend = function(a, c) {
				b.formData ? c.data = b.formData: c.data = d,
				h && h.call(this, a, c)
			},
			a.ajax(g)
		}
		function k(c) {
			function e(a) {
				var b = null;
				try {
					a.contentWindow && (b = a.contentWindow.document)
				} catch(a) {
					d("cannot get iframe.contentWindow document: " + a)
				}
				if (b) return b;
				try {
					b = a.contentDocument ? a.contentDocument: a.document
				} catch(c) {
					d("cannot get iframe.contentDocument: " + c),
					b = a.document
				}
				return b
			}
			function g() {
				function b() {
					try {
						var a = e(q).readyState;
						d("state = " + a),
						a && "uninitialized" === a.toLowerCase() && setTimeout(b, 50)
					} catch(a) {
						d("Server abort: ", a, " (", a.name, ")"),
						h(2),
						w && clearTimeout(w),
						w = void 0
					}
				}
				var c = o.attr2("target"),
				f = o.attr2("action"),
				g = o.attr("enctype") || o.attr("encoding") || "multipart/form-data";
				x.setAttribute("target", n),
				l && !/post/i.test(l) || x.setAttribute("method", "POST"),
				f !== k.url && x.setAttribute("action", k.url),
				k.skipEncodingOverride || l && !/post/i.test(l) || o.attr({
					encoding: "multipart/form-data",
					enctype: "multipart/form-data"
				}),
				k.timeout && (w = setTimeout(function() {
					v = !0,
					h(1)
				},
				k.timeout));
				var i = [];
				try {
					if (k.extraData) for (var j in k.extraData) k.extraData.hasOwnProperty(j) && (a.isPlainObject(k.extraData[j]) && k.extraData[j].hasOwnProperty("name") && k.extraData[j].hasOwnProperty("value") ? i.push(a('<input type="hidden" name="' + k.extraData[j].name + '">', z).val(k.extraData[j].value).appendTo(x)[0]) : i.push(a('<input type="hidden" name="' + j + '">', z).val(k.extraData[j]).appendTo(x)[0]));
					k.iframeTarget || p.appendTo(A),
					q.attachEvent ? q.attachEvent("onload", h) : q.addEventListener("load", h, !1),
					setTimeout(b, 15);
					try {
						x.submit()
					} catch(a) {
						var m = document.createElement("form").submit;
						m.apply(x)
					}
				} finally {
					x.setAttribute("action", f),
					x.setAttribute("enctype", g),
					c ? x.setAttribute("target", c) : o.removeAttr("target"),
					a(i).remove()
				}
			}
			function h(b) {
				if (!r.aborted && !F) {
					if (E = e(q), E || (d("cannot access response document"), b = 2), 1 === b && r) return r.abort("timeout"),
					void y.reject(r, "timeout");
					if (2 === b && r) return r.abort("server abort"),
					void y.reject(r, "error", "server abort");
					if (E && E.location.href !== k.iframeSrc || v) {
						q.detachEvent ? q.detachEvent("onload", h) : q.removeEventListener("load", h, !1);
						var c, f = "success";
						try {
							if (v) throw "timeout";
							var g = "xml" === k.dataType || E.XMLDocument || a.isXMLDoc(E);
							if (d("isXml=" + g), !g && window.opera && (null === E.body || !E.body.innerHTML) && --G) return d("requeing onLoad callback, DOM not available"),
							void setTimeout(h, 250);
							var i = E.body ? E.body: E.documentElement;
							r.responseText = i ? i.innerHTML: null,
							r.responseXML = E.XMLDocument ? E.XMLDocument: E,
							g && (k.dataType = "xml"),
							r.getResponseHeader = function(a) {
								return {
									"content-type": k.dataType
								} [a.toLowerCase()]
							},
							i && (r.status = Number(i.getAttribute("status")) || r.status, r.statusText = i.getAttribute("statusText") || r.statusText);
							var j = (k.dataType || "").toLowerCase(),
							l = /(json|script|text)/.test(j);
							if (l || k.textarea) {
								var n = E.getElementsByTagName("textarea")[0];
								if (n) r.responseText = n.value,
								r.status = Number(n.getAttribute("status")) || r.status,
								r.statusText = n.getAttribute("statusText") || r.statusText;
								else if (l) {
									var o = E.getElementsByTagName("pre")[0],
									s = E.getElementsByTagName("body")[0];
									o ? r.responseText = o.textContent ? o.textContent: o.innerText: s && (r.responseText = s.textContent ? s.textContent: s.innerText)
								}
							} else "xml" === j && !r.responseXML && r.responseText && (r.responseXML = H(r.responseText));
							try {
								D = J(r, j, k)
							} catch(a) {
								f = "parsererror",
								r.error = c = a || f
							}
						} catch(a) {
							d("error caught: ", a),
							f = "error",
							r.error = c = a || f
						}
						r.aborted && (d("upload aborted"), f = null),
						r.status && (f = r.status >= 200 && r.status < 300 || 304 === r.status ? "success": "error"),
						"success" === f ? (k.success && k.success.call(k.context, D, "success", r), y.resolve(r.responseText, "success", r), m && a.event.trigger("ajaxSuccess", [r, k])) : f && (void 0 === c && (c = r.statusText), k.error && k.error.call(k.context, r, f, c), y.reject(r, "error", c), m && a.event.trigger("ajaxError", [r, k, c])),
						m && a.event.trigger("ajaxComplete", [r, k]),
						m && !--a.active && a.event.trigger("ajaxStop"),
						k.complete && k.complete.call(k.context, r, f),
						F = !0,
						k.timeout && clearTimeout(w),
						setTimeout(function() {
							k.iframeTarget ? p.attr("src", k.iframeSrc) : p.remove(),
							r.responseXML = null
						},
						100)
					}
				}
			}
			var i, j, k, m, n, p, q, r, t, u, v, w, x = o[0],
			y = a.Deferred();
			if (y.abort = function(a) {
				r.abort(a)
			},
			c) for (j = 0; j < s.length; j++) i = a(s[j]),
			f ? i.prop("disabled", !1) : i.removeAttr("disabled");
			k = a.extend(!0, {},
			a.ajaxSettings, b),
			k.context = k.context || k,
			n = "jqFormIO" + (new Date).getTime();
			var z = x.ownerDocument,
			A = o.closest("body");
			if (k.iframeTarget ? (p = a(k.iframeTarget, z), u = p.attr2("name"), u ? n = u: p.attr2("name", n)) : (p = a('<iframe name="' + n + '" src="' + k.iframeSrc + '" />', z), p.css({
				position: "absolute",
				top: "-1000px",
				left: "-1000px"
			})), q = p[0], r = {
				aborted: 0,
				responseText: null,
				responseXML: null,
				status: 0,
				statusText: "n/a",
				getAllResponseHeaders: function() {},
				getResponseHeader: function() {},
				setRequestHeader: function() {},
				abort: function(b) {
					var c = "timeout" === b ? "timeout": "aborted";
					d("aborting upload... " + c),
					this.aborted = 1;
					try {
						q.contentWindow.document.execCommand && q.contentWindow.document.execCommand("Stop")
					} catch(a) {}
					p.attr("src", k.iframeSrc),
					r.error = c,
					k.error && k.error.call(k.context, r, c, b),
					m && a.event.trigger("ajaxError", [r, k, c]),
					k.complete && k.complete.call(k.context, r, c)
				}
			},
			m = k.global, m && 0 == a.active++&&a.event.trigger("ajaxStart"), m && a.event.trigger("ajaxSend", [r, k]), k.beforeSend && k.beforeSend.call(k.context, r, k) === !1) return k.global && a.active--,
			y.reject(),
			y;
			if (r.aborted) return y.reject(),
			y; (t = x.clk) && (u = t.name) && !t.disabled && (k.extraData = k.extraData || {},
			k.extraData[u] = t.value, "image" === t.type && (k.extraData[u + ".x"] = x.clk_x, k.extraData[u + ".y"] = x.clk_y));
			var B = a("meta[name=csrf-token]").attr("content"),
			C = a("meta[name=csrf-param]").attr("content");
			C && B && (k.extraData = k.extraData || {},
			k.extraData[C] = B),
			k.forceSync ? g() : setTimeout(g, 10);
			var D, E, F, G = 50,
			H = a.parseXML ||
			function(a, b) {
				return window.ActiveXObject ? (b = new ActiveXObject("Microsoft.XMLDOM"), b.async = "false", b.loadXML(a)) : b = (new DOMParser).parseFromString(a, "text/xml"),
				b && b.documentElement && "parsererror" !== b.documentElement.nodeName ? b: null
			},
			I = a.parseJSON ||
			function(a) {
				return window.eval("(" + a + ")")
			},
			J = function(b, c, d) {
				var e = b.getResponseHeader("content-type") || "",
				f = ("xml" === c || !c) && e.indexOf("xml") >= 0,
				g = f ? b.responseXML: b.responseText;
				return f && "parsererror" === g.documentElement.nodeName && a.error && a.error("parsererror"),
				d && d.dataFilter && (g = d.dataFilter(g, c)),
				"string" == typeof g && (("json" === c || !c) && e.indexOf("json") >= 0 ? g = I(g) : ("script" === c || !c) && e.indexOf("javascript") >= 0 && a.globalEval(g)),
				g
			};
			return y
		}
		if (!this.length) return d("ajaxSubmit: skipping submit process - no element selected"),
		this;
		var l, m, n, o = this;
		"function" == typeof b ? b = {
			success: b
		}: "string" == typeof b || b === !1 && arguments.length > 0 ? (b = {
			url: b,
			data: c,
			dataType: g
		},
		"function" == typeof h && (b.success = h)) : void 0 === b && (b = {}),
		l = b.method || b.type || this.attr2("method"),
		m = b.url || this.attr2("action"),
		n = "string" == typeof m ? a.trim(m) : "",
		n = n || window.location.href || "",
		n && (n = (n.match(/^([^#]+)/) || [])[1]),
		b = a.extend(!0, {
			url: n,
			success: a.ajaxSettings.success,
			type: l || a.ajaxSettings.type,
			iframeSrc: /^https/i.test(window.location.href || "") ? "javascript:false": "about:blank"
		},
		b);
		var p = {};
		if (this.trigger("form-pre-serialize", [this, b, p]), p.veto) return d("ajaxSubmit: submit vetoed via form-pre-serialize trigger"),
		this;
		if (b.beforeSerialize && b.beforeSerialize(this, b) === !1) return d("ajaxSubmit: submit aborted via beforeSerialize callback"),
		this;
		var q = b.traditional;
		void 0 === q && (q = a.ajaxSettings.traditional);
		var r, s = [],
		t = this.formToArray(b.semantic, s, b.filtering);
		if (b.data) {
			var u = a.isFunction(b.data) ? b.data(t) : b.data;
			b.extraData = u,
			r = a.param(u, q)
		}
		if (b.beforeSubmit && b.beforeSubmit(t, this, b) === !1) return d("ajaxSubmit: submit aborted via beforeSubmit callback"),
		this;
		if (this.trigger("form-submit-validate", [t, this, b, p]), p.veto) return d("ajaxSubmit: submit vetoed via form-submit-validate trigger"),
		this;
		var v = a.param(t, q);
		r && (v = v ? v + "&" + r: r),
		"GET" === b.type.toUpperCase() ? (b.url += (b.url.indexOf("?") >= 0 ? "&": "?") + v, b.data = null) : b.data = v;
		var w = [];
		if (b.resetForm && w.push(function() {
			o.resetForm()
		}), b.clearForm && w.push(function() {
			o.clearForm(b.includeHidden)
		}), !b.dataType && b.target) {
			var x = b.success ||
			function() {};
			w.push(function(c, d, e) {
				var f = arguments,
				g = b.replaceTarget ? "replaceWith": "html";
				a(b.target)[g](c).each(function() {
					x.apply(this, f)
				})
			})
		} else b.success && (a.isArray(b.success) ? a.merge(w, b.success) : w.push(b.success));
		if (b.success = function(a, c, d) {
			for (var e = b.context || this,
			f = 0,
			g = w.length; f < g; f++) w[f].apply(e, [a, c, d || o, o])
		},
		b.error) {
			var y = b.error;
			b.error = function(a, c, d) {
				var e = b.context || this;
				y.apply(e, [a, c, d, o])
			}
		}
		if (b.complete) {
			var z = b.complete;
			b.complete = function(a, c) {
				var d = b.context || this;
				z.apply(d, [a, c, o])
			}
		}
		var A = a("input[type=file]:enabled", this).filter(function() {
			return "" !== a(this).val()
		}),
		B = A.length > 0,
		C = "multipart/form-data",
		D = o.attr("enctype") === C || o.attr("encoding") === C,
		E = e.fileapi && e.formdata;
		d("fileAPI :" + E);
		var F, G = (B || D) && !E;
		b.iframe !== !1 && (b.iframe || G) ? b.closeKeepAlive ? a.get(b.closeKeepAlive,
		function() {
			F = k(t)
		}) : F = k(t) : F = (B || D) && E ? j(t) : a.ajax(b),
		o.removeData("jqxhr").data("jqxhr", F);
		for (var H = 0; H < s.length; H++) s[H] = null;
		return this.trigger("form-submit-notify", [this, b]),
		this
	},
	a.fn.ajaxForm = function(e, f, g, h) {
		if (("string" == typeof e || e === !1 && arguments.length > 0) && (e = {
			url: e,
			data: f,
			dataType: g
		},
		"function" == typeof h && (e.success = h)), e = e || {},
		e.delegation = e.delegation && a.isFunction(a.fn.on), !e.delegation && 0 === this.length) {
			var i = {
				s: this.selector,
				c: this.context
			};
			return ! a.isReady && i.s ? (d("DOM not ready, queuing ajaxForm"), a(function() {
				a(i.s, i.c).ajaxForm(e)
			}), this) : (d("terminating; zero elements found by selector" + (a.isReady ? "": " (DOM not ready)")), this)
		}
		return e.delegation ? (a(document).off("submit.form-plugin", this.selector, b).off("click.form-plugin", this.selector, c).on("submit.form-plugin", this.selector, e, b).on("click.form-plugin", this.selector, e, c), this) : this.ajaxFormUnbind().on("submit.form-plugin", e, b).on("click.form-plugin", e, c)
	},
	a.fn.ajaxFormUnbind = function() {
		return this.off("submit.form-plugin click.form-plugin")
	},
	a.fn.formToArray = function(b, c, d) {
		var f = [];
		if (0 === this.length) return f;
		var g, h = this[0],
		i = this.attr("id"),
		j = b || void 0 === h.elements ? h.getElementsByTagName("*") : h.elements;
		if (j && (j = a.makeArray(j)), i && (b || /(Edge|Trident)\//.test(navigator.userAgent)) && (g = a(':input[form="' + i + '"]').get(), g.length && (j = (j || []).concat(g))), !j || !j.length) return f;
		a.isFunction(d) && (j = a.map(j, d));
		var k, l, m, n, o, p, q;
		for (k = 0, p = j.length; k < p; k++) if (o = j[k], (m = o.name) && !o.disabled) if (b && h.clk && "image" === o.type) h.clk === o && (f.push({
			name: m,
			value: a(o).val(),
			type: o.type
		}), f.push({
			name: m + ".x",
			value: h.clk_x
		},
		{
			name: m + ".y",
			value: h.clk_y
		}));
		else if ((n = a.fieldValue(o, !0)) && n.constructor === Array) for (c && c.push(o), l = 0, q = n.length; l < q; l++) f.push({
			name: m,
			value: n[l]
		});
		else if (e.fileapi && "file" === o.type) {
			c && c.push(o);
			var r = o.files;
			if (r.length) for (l = 0; l < r.length; l++) f.push({
				name: m,
				value: r[l],
				type: o.type
			});
			else f.push({
				name: m,
				value: "",
				type: o.type
			})
		} else null !== n && void 0 !== n && (c && c.push(o), f.push({
			name: m,
			value: n,
			type: o.type,
			required: o.required
		}));
		if (!b && h.clk) {
			var s = a(h.clk),
			t = s[0];
			m = t.name,
			m && !t.disabled && "image" === t.type && (f.push({
				name: m,
				value: s.val()
			}), f.push({
				name: m + ".x",
				value: h.clk_x
			},
			{
				name: m + ".y",
				value: h.clk_y
			}))
		}
		return f
	},
	a.fn.formSerialize = function(b) {
		return a.param(this.formToArray(b))
	},
	a.fn.fieldSerialize = function(b) {
		var c = [];
		return this.each(function() {
			var d = this.name;
			if (d) {
				var e = a.fieldValue(this, b);
				if (e && e.constructor === Array) for (var f = 0,
				g = e.length; f < g; f++) c.push({
					name: d,
					value: e[f]
				});
				else null !== e && void 0 !== e && c.push({
					name: this.name,
					value: e
				})
			}
		}),
		a.param(c)
	},
	a.fn.fieldValue = function(b) {
		for (var c = [], d = 0, e = this.length; d < e; d++) {
			var f = this[d],
			g = a.fieldValue(f, b);
			null === g || void 0 === g || g.constructor === Array && !g.length || (g.constructor === Array ? a.merge(c, g) : c.push(g))
		}
		return c
	},
	a.fieldValue = function(b, c) {
		var d = b.name,
		e = b.type,
		f = b.tagName.toLowerCase();
		if (void 0 === c && (c = !0), c && (!d || b.disabled || "reset" === e || "button" === e || ("checkbox" === e || "radio" === e) && !b.checked || ("submit" === e || "image" === e) && b.form && b.form.clk !== b || "select" === f && b.selectedIndex === -1)) return null;
		if ("select" === f) {
			var g = b.selectedIndex;
			if (g < 0) return null;
			for (var h = [], i = b.options, j = "select-one" === e, k = j ? g + 1 : i.length, l = j ? g: 0; l < k; l++) {
				var m = i[l];
				if (m.selected && !m.disabled) {
					var n = m.value;
					if (n || (n = m.attributes && m.attributes.value && !m.attributes.value.specified ? m.text: m.value), j) return n;
					h.push(n)
				}
			}
			return h
		}
		return a(b).val().replace(/\r?\n/g, "\r\n")
	},
	a.fn.clearForm = function(b) {
		return this.each(function() {
			a("input,select,textarea", this).clearFields(b)
		})
	},
	a.fn.clearFields = a.fn.clearInputs = function(b) {
		var c = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i;
		return this.each(function() {
			var d = this.type,
			e = this.tagName.toLowerCase();
			c.test(d) || "textarea" === e ? this.value = "": "checkbox" === d || "radio" === d ? this.checked = !1 : "select" === e ? this.selectedIndex = -1 : "file" === d ? /MSIE/.test(navigator.userAgent) ? a(this).replaceWith(a(this).clone(!0)) : a(this).val("") : b && (b === !0 && /hidden/.test(d) || "string" == typeof b && a(this).is(b)) && (this.value = "")
		})
	},
	a.fn.resetForm = function() {
		return this.each(function() {
			var b = a(this),
			c = this.tagName.toLowerCase();
			switch (c) {
			case "input":
				this.checked = this.defaultChecked;
			case "textarea":
				return this.value = this.defaultValue,
				!0;
			case "option":
			case "optgroup":
				var d = b.parents("select");
				return d.length && d[0].multiple ? "option" === c ? this.selected = this.defaultSelected: b.find("option").resetForm() : d.resetForm(),
				!0;
			case "select":
				return b.find("option").each(function(a) {
					if (this.selected = this.defaultSelected, this.defaultSelected && !b[0].multiple) return b[0].selectedIndex = a,
					!1
				}),
				!0;
			case "label":
				var e = a(b.attr("for")),
				f = b.find("input,select,textarea");
				return e[0] && f.unshift(e[0]),
				f.resetForm(),
				!0;
			case "form":
				return ("function" == typeof this.reset || "object" == typeof this.reset && !this.reset.nodeType) && this.reset(),
				!0;
			default:
				return b.find("form,input,label,select,textarea").resetForm(),
				!0
			}
		})
	},
	a.fn.enable = function(a) {
		return void 0 === a && (a = !0),
		this.each(function() {
			this.disabled = !a
		})
	},
	a.fn.selected = function(b) {
		return void 0 === b && (b = !0),
		this.each(function() {
			var c = this.type;
			if ("checkbox" === c || "radio" === c) this.checked = b;
			else if ("option" === this.tagName.toLowerCase()) {
				var d = a(this).parent("select");
				b && d[0] && "select-one" === d[0].type && d.find("option").selected(!1),
				this.selected = b
			}
		})
	},
	a.fn.ajaxSubmit.debug = !1
});
 类似资料: