大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
本文实例为大家分享了jquery实现动态添加附件的具体代码,供大家参考,具体内容如下
创建HTML页面
项目中实现的原代码,无删减直接贴上。具体请参考“添加附件”按钮相关操作。
注意引入:cardRansomManage.js,ajaxfileupload.js.
创建Javascript库
cardRansomManage.js
//设置面罩的z-index,打开进度条 function setPopupZ_index() { $("#popupDiv_bgDiv_1").css("z-index", "550"); bcd_openPopUpDailog(300, 'loading'); //进度条 } /** * 编辑、查看、提交页面 资源控制 */ var $fileMixSize = 10; //允许上传附件数 var $fileCurSize = 0; //已上传并保存附件数 var $fileSize = 0; //当前新增附件操作次数 var $delFiles =""; //记录 删除已保存附件 var $flag = 0; //数据校验 0:附件无效; 1:无附件提交; 2:附件有效 $(document).ready(function(){ $fileCurSize = $("input[name='attach']").size(); initialResource(); bindListener(); }); function initialResource(){ var orderStatus = $("#orderStatus").val(); var isLoginUser = $("#isLoginUser").val(); var btnSubmit = $("#btnSubmit"); var btnAudit = $("#btnAudit"); var btnRefuse = $("#btnRefuse"); if(isLoginUser=="true"){ if(orderStatus==0||orderStatus==3){//草稿、驳回状态 // addFile(); if(btnAudit != undefined){ btnAudit.hide(); } if(btnRefuse != undefined){ btnRefuse.hide(); } }else {//orderStatus:1(申请),2(审核) $("a[name='rmlinkattach']").remove(); $("#toolbar").remove(); } }else{ if(orderStatus!=1){ $("#toolbar").remove(); $("a[name='rmlinkattach']").remove(); }else{ $("#btnSave").hide(); $("a[name='rmlinkattach']").hide(); if(btnSubmit != undefined){ btnSubmit.hide(); } } } } function doCloseFunction(){ window.location.href="query?orderDetail&orderNo=" rel="external nofollow" ; } function addFile(){ $fileSize = $("[name='uploadfiles']").size(); if($fileSize < $fileMixSize - $fileCurSize){ var $fileTemple=$("#fileTemplate >div").clone(); var tid = "uploadfiles0"+new Date().getTime(); $fileTemple.find(":file").attr("id",tid); $fileTemple.find(":file").attr("name","uploadfiles"); $fileTemple.find("a").attr("name","rmlink"); $("#mdiv").append($fileTemple); bindListener(); $fileSize++; }else{ alertDiv.create("alertDiv","最大上传文件数为:"+$fileMixSize+"."); } } function saveFile(){ operSubmit("0"); $delFiles = ""; } function submitApply(){ operSubmit("1"); $delFiles =""; } function submitAudit(){ var orderStatus = $("#orderStatus").val(); //审核人:只允许处理审核状态的赎回单 if(orderStatus==1){ $.messager.confirm('请确认', '您要批准此赎回申请单?', function(r) { if(r){ operSubmit("2"); //审批通过 } }); $delFiles =""; }else{ alertDiv.create("alertDiv","赎回单当前状态,不允许提交!"); } } function submitRefuse(){ var orderStatus = $("#orderStatus").val(); //审核人:只允许处理审核状态的赎回单 if(orderStatus==1){ $.messager.confirm('请确认', '您要驳回此赎回申请单?', function(r) { if(r){ operSubmit("3"); //驳回 } }); }else{ alertDiv.create("alertDiv","赎回单当前状态,不允许提交!"); } } function downLoadFile(attachmentId){ $('#attachmentId').val(attachmentId); $('#downloadform').attr('action', 'downLoad'); $("#downloadform").submit(); } function bindListener(){ $("a[name=rmlink]").unbind().click(function(){ $(this).parent().parent().remove(); $fileSize--; }) } function rmlinkAttach(attach, obj){ $.messager.confirm('请确认', '您要删除当前所选项目?', function(r) { if(r){ $delFiles += ""+attach +","; $fileCurSize -=1; $(obj).parent().parent().remove(); } }); } //处理查询返回的信息 function callBack(order) { var html = ""; var orderStatus = order.orderStatus; //var orderStatus = record['record'].orderStatus; $("#orderStatus").val(orderStatus); $("#mdiv").empty();//清空以前的数据 $("#freshdiv").empty(); $(order.attachment).each( function(i, attach) { html += ""; }); var $container = $("#freshdiv"); $container.append(html);//追加新的数据 } function refreshRes(order,orderStatusName){ $("#orderNo").val(order.orderNo); $("#orderStatus").val(order.orderStatus); $("#orderStatus option[value='"+order.orderStatus+"']").attr("selected","selected"); initialResource(); //$.post("query?Detail",order,callBack, "json"); callBack(order) $fileCurSize = $("input[name='attach']").size(); } function operSubmit(status){ validateUploadfiles(); if($flag==2){ var order = { orderNo: $("#orderNo").val(), orderStatus: status, attachments: $delFiles }; fileupload("save",order,"query?orderDetail&orderNo="); }else if($flag==1){ var order = { orderNo: $("#orderNo").val(), orderStatus: status, attachments: $delFiles }; $.post("save?unUpload", order, function(data){ if (data.success) { refreshRes(data['order']); alertDiv.create("alertDiv", data.obj); } else { alertDiv.create("alertDiv", data.obj); } }, "json"); }else{ alertDiv.create("alertDiv","附件不能为空,请添加有效附件!"); } } function validateUploadfiles(){ var files = $("input[name='uploadfiles']"); if(files.size()>0){ $.each(files,function(i, file){ if(file.value==undefined || file.value==""){ alertDiv.create("alertDiv","新增附件不能为空,请上传!"); $flag = 0; }else{ $flag = 2; } }); }else{ $flag=1; } } function fileupload(url,order,successUrl){ var files = $("input[name='uploadfiles']"); var uploadfiles = []; $.each(files,function(i, file){ if(file.value!=undefined || file.value!=""){ uploadfiles.push(files[i].id) } }); $.ajaxFileUpload({ url: url, secureuri : false, type: 'post', dataType: "json", fileElementId: uploadfiles, data: order, beforeSend: function() { setPopupZ_index(); }, success: function(result) { if (result.success) { refreshRes(result['order']); alertDiv.create("alertDiv", result.obj); } else { alertDiv.create("alertDiv", result.obj); } }, error: function(result) { alertDiv.create("alertDiv", "赎回申请信息出错,请稍后重试!"); }, complete: function() { //$("#btnsave").removeAttr("disabled"); } }); }
ajaxfileupload.js
jQuery.extend({ 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] ); } }, createUploadIframe: function(id, uri) { //create frame var frameId = 'jUploadFrame' + id; var iframeHtml = ''; jQuery(iframeHtml).appendTo(document.body); return jQuery('#' + frameId).get(0); }, createUploadForm: function(id, fileElementId, data) { //create form var formId = 'jUploadForm' + id; var fileId = 'jUploadFile' + id; var form = jQuery(''); if(data) { for(var i in data) { jQuery('').appendTo(form); } } if(typeof(fileElementId) == 'string'){ fileElementId = [fileElementId]; } for (var i = 0; i < fileElementId.length; i ++) { var oldElement = jQuery('#' + fileElementId[i]); var newElement = jQuery(oldElement).clone(); jQuery(oldElement).attr('id', fileId); jQuery(oldElement).before(newElement); jQuery(oldElement).appendTo(form); } // var oldElement = jQuery('#' + fileElementId); // var newElement = jQuery(oldElement).clone(); // jQuery(oldElement).attr('id', fileId); // jQuery(oldElement).before(newElement); // jQuery(oldElement).appendTo(form); //set attributes jQuery(form).css('position', 'absolute'); jQuery(form).css('top', '-1200px'); jQuery(form).css('left', '-1200px'); jQuery(form).appendTo('body'); 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); var id = new Date().getTime() var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false: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 { jQuery(io).remove(); jQuery(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 form = jQuery('#' + formId); jQuery(form).attr('action', s.url); jQuery(form).attr('method', 'POST'); jQuery(form).attr('target', frameId); if(form.encoding) { jQuery(form).attr('encoding', 'multipart/form-data'); } else { jQuery(form).attr('enctype', 'multipart/form-data'); } jQuery(form).submit(); } catch(e) { jQuery.handleError(s, xml, null, e); } jQuery('#' + frameId).load(uploadCallback ); 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" ) 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("
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。