jquery 的form表单通用处理

宏哥 发布于 2013/07/19 23:37
阅读 1K+
收藏 2

首先感谢 CCTV以及OSC的朋友对优化的帮助

只是做了第一步清理:

/**
 * Generic Form processing js
 * Support Ajax Form Hint&Reload
 */

/**
 * Push button action data into form
 */
function ajax_form_button(e){
	btn = $(this);
	var btn_action = { name:'btn_action',value:btn.attr('value') };
	$(this).parents('form').data('btn_action',btn_action);
}

function ajax_form_post(e){
	var form = $(this);
	var errHint = form.find(".formError").first();
	if(errHint.size() == 0){
		errHint = $("#pageError");
	}
	errHint.text('').hide();

	//Cleanup the pageError
	if(!e.isDefaultPrevented()){
		//Hide all .formError
		$.blockUI({ message:"{__('L_Processing')}" });
		formArray = form.serializeArray();
		if(btn_action = form.data('btn_action')){
			formArray.push(btn_action);
			form.removeData('btn_action');
		}else{
			btn_action = { name:'btn_action',value:'' };
		}

		$.post(form.attr('action'), formArray,function(json){
				$.unblockUI();
				if(json.code === true){
					retData = "{__('R_Success')}!";
					if(json.data){
						retData = json.data;	
					}

					//TODO Add suppport to allow save and stay
					if(btn_action.value =='saveonly'){
						$.blockUI({ message:retData });$.unblockUI();
					} //if there is returi set, then return to uri
					else if(returi = form.attr('returi')){
						window.location = returi;
					//Else if reload is set, then will be reload
					}else if(form.attr('reload')){
						window.location.reload();
					}else{
						$.blockUI({ message:retData });$.unblockUI();

					}
				}
				else{
					if(typeof (json.data) == 'string'){
						errHint.html(json.data).show();
					}else{
						errHint.html("{Html::text(__('E_FORM'))}").show();
						for(var p in json.data){
							var msg = eval("json.data."+p);
							//Process hidden value,None hidden input should has refid refered to hidden value
							//Showing the Server message to ref 
							var ele = form.find("[type=hidden][name="+p+"]");
							if(ele.length){
								eval("delete json.data."+p);
								refid = ele.attr("id");
								refname = form.find("[refid="+refid+"]").attr("name");
								eval("json.data."+refname+"="+'"'+msg+'"');
							}
							//Process the non-exist property
							//@TODO add support SLTS
							var inputele = form.find(":input[name="+p+"]");
							if(!inputele.length){
								var tdele = form.find("td[name='"+p+"']");
								if(tdele.length){ //Calculate the POS of TD
									conf = $.tools.validator.conf;
									errmsg = $(conf.message).html($("<span/>").text(msg).html()) .addClass(conf.messageClass).append(tdele);
									//store data into TD
									tdele.data("msg.el", errmsg);
									errmsg.css({visibility: 'hidden'}).find("p").remove();
									errmsg.css({ visibility: 'visible' }).fadeIn(conf.speed);     

								}else{
									errHint.html(msg).show();
									eval("delete json.data."+p);
								}
							}
						}
					}
					/*
					 * Checking the hidden values 
					 */
					form.data("validator").invalidate(json.data);
				} },'json');
				e.preventDefault();
	}else{
		errHint.html("{Html::text(__('E_FORM'))}").show();
	}
}

function ajax_link_req(){
	var l = $(this);
	hint = l.attr('hint');
	if(hint){
		var errHint = $(l.attr('hint'));
		errHint.text('').hide();
	}
	//If the confirm message is set, then should be confirmed from client
	if(l.attr('confirm')){
		if(!confirm(l.attr('confirm'))){
			return false;
		}
	}

	$.blockUI({ message:"{__('L_Processing')}" });
	$.get(l.attr('href'),function(json){
			if(json.code == true){
				retData = "{__('R_Success')}!";
				if(json.data){
					retData = json.data;	
				}
				//IF Require warning before
				if(successwarn= l.attr('successwarn')){
					alert(successwarn);
				}
				//Could define return URI
				if(returi = l.attr('returi')){
					window.location = returi;
				}
				else if(l.attr('reload')){
					window.location.reload();
				}
				else{
					$.blockUI({ message:retData });$.unblockUI();
				}
			}else{
				$.unblockUI();
				//Only could support Text errmsg
				if(hint){
					errHint.text(json.data).show();
				}else{
					alert(json.data);
				}
			}},'json');
	return false;
}

/**
 * Supporting the button base navigation
 */
function btn_nav(){
	var input = $(this);
	var href = input.attr("href");
	if(href){
		window.location = href;
	}else{
		alert("Href not set");
	}
	return false;
}

/**
 * Support button base get methon request
 */
function btn_req(){
	var input = $(this);
	var href = input.attr("href");

	hint = input.attr('hint');
	if(hint){
		var errHint = $(hint).fist();
		if(errHint.size() == 0){
			errHint = $("#pageError");
		}
		errHint.text('').hide();
	}

	$.get(href,function(json){
			if(json.code == true){
			if(returi = input.attr('returi')){
				window.location = returi;
			}
			else if(input.attr("reload")){
				window.location.reload();
			} else{
					retData = "{__('R_Success')}!";
					if(json.data){
						retData = json.data;	
					}
					$.blockUI({ message:retData });$.unblockUI();
			}
			}else{
			if(hint){
				errHint.html(json.data).show();
			}else{
				alert(json.data);
			}

			}
			},'json');
	return false;
}

var PmdMultiCheck = function(){
	//event.preventDefault();
	var action = $(this);
	var url = action.attr('url');
	var op = action.attr('op');
	var row_lov_pmd_id = action.attr('row_lov_pmd_id');
	$.get(url +row_lov_pmd_id+'_' + op ,function(json){
		if(json == true){
			if(op == '1'){
				action.attr('op','0');
			}else{
				action.attr('op','1');
			}
			action.one('click',PmdMultiCheck);
			}else{
			action.one('click',PmdMultiCheck);
			event.preventDefault();
		}
	},'json');
}

function classchange(lclass){
	var lc= $(lclass);
	var urlbase = lc.attr("urlbase");
	var attrid= lc.attr("attrid");
	var refid = lc.attr("refid");
	lc.nextAll().remove();
	if(lc.find(":selected").attr('is-leaf')=="{DB::T}"){
		$("#"+refid).val(lc.val());
		lc.after("<img src='/s.gif' class='successimg'/>");
	}else{
		if(lc.val()==""){
			return ;
		}
		var cid = lc.find(":selected").attr('pid');
		$.get(urlbase+attrid+"_"+cid, function(data){
				lc.after(data);
				});
	}
}

function ajax_pmd_remove_attach(){
	var l = $(this);
	$.get(l.attr('href'),function(json){
			if(json.code == true){
			if(l.attr('rmid')){
				$("#"+l.attr('rmid')).remove();
				if($(".item").length==0){
					$("#pmd-files").hide();
				}
			}
			}else{
			alert(json.data);
			}
			},'json');
	return false;
}

var pmdFineUpload = function(){
	uploadObj = $(this);
	pmd_id = uploadObj.attr('pmd_id');
	sid =  uploadObj.attr('sid');
	uploadUrl = uploadObj.attr('uploadUrl');
	itemUrl = uploadObj.attr('itemUrl');

	uploadObj.fineUploader({
		request: {
		endpoint:uploadUrl,
		params:{ 'sessionid': sid }, 
		paramsInBody:true,
		inputName:'Filedata',
		},
		text: {
			uploadButton: "{__('L_ClickUpload')}"
		},
		multiple: true,
		debug: true
	}).on('Upload',function(){
			$(".qq-drop-processing").show();
		}
		). on('complete', function(event, id, fileName, responseJSON) { 
			if(responseJSON.success){
			//Update Image List
			file_id = responseJSON.data;
			$.get(itemUrl+file_id,function(data){ 
						$(".scrollable").data("scrollable").addItem(data);
						$(".ajax-pmd-remove_attach").one('click',ajax_pmd_remove_attach);
				});
			$(".scrollable").show();
			$("#pmd-files").show();
			}else{
				alert("Failed:"+responseJSON.data);
			}

			inProgress = $(this).fineUploader('getInProgress');
			if(inProgress == 0){
			//window.location.reload();
				$(".qq-upload-list").hide();
				$(".qq-drop-processing").hide();
			}
		}) ;
}

var advance_validate = function(errors, event) {
	var conf = this.getConf();
	// loop errors
	$.each(errors, function(index, error) {
			// add error class into input Dom element
			var input = error.input;					

			input.addClass(conf.errorClass);

			// get handle to the error container
			var msg = input.data("msg.el"); 

			// create Error data if not present, and add error class for input
			// "msg.el" data is linked to error message Dom Element
			if (!msg) { 
			//msg = $(conf.message).addClass(conf.messageClass).insertAfter(input);
			msg = $(conf.message).addClass(conf.messageClass).appendTo(input.parent());
			input.data("msg.el", msg);
			}  

			// clear the container 
			msg.css({visibility: 'hidden'}).find("span").remove();

			// populate messages
			$.each(error.messages, function(i, m) { 
					$("<span/>").html(m).appendTo(msg);			
					});

			// make sure the width is not full body width so it can be positioned correctly
			if (msg.outerWidth() == msg.parent().width()) {
				msg.add(msg.find("span"));		
			} 

			//insert into correct position (relative to the field)

			msg.css({ visibility: 'visible'}) .fadeIn(conf.speed);     
			msg.parent().addClass("colError");
	});
}

advance_inputs = function(inputs) {
	var conf = this.getConf();				
	inputs.removeClass(conf.errorClass).each(function() {
			var msg = $(this).data("msg.el");
			if (msg) {
			msg.hide();
			msg.parent().removeClass("colError");
			}
			});
	if($(".colError").size() == 0){	
		var form = $(this);
		var errHint = form.find(".formError").first();
		if(errHint.size() == 0){
			errHint = $("#pageError");
			errHint.text('').hide();
		}
	}

}

$(document).ready(function() {
		$(document).ajaxStart(function(){
			//Clean up the Ajax request Page Level Error
			$("#pageError").text('').hide();
			//Clean up teh Form Error
			$(".formError").text('').hide();
			//Blocking all ajax processing
			$.blockUI({ message:"{__('L_Processing')}" });
			});
		$(document).ajaxStop(function(){
			$.unblockUI();
			});
		$(document).ajaxError(function(event, request, settings){
			alert('Ajax Request Error! URL='+settings.url);
			$.unblockUI();
			});

		$.tools.validator.fn("[data-equals]", { "{lang}":"{__('E_NOTEQUAL')}" }, function(input) {
			var name = input.attr("data-equals"),
			field = this.getInputs().filter("[name=" + name + "]");
			return input.val() == field.val() ? true : [name];
			});

		$.tools.validator.addEffect("advanced", advance_validate,advance_inputs);

		$('.ajax_link_req').click(ajax_link_req);
		//Client validation for the hidden ID 
		$.tools.validator.fn("[hidden-id]", function(input) {
			var refid = input.attr("hidden-id");
			field = $("#" + refid + ""); 
			return field.val() ? true : field.attr('msg'); 
			});

		$(".ajax_form_post").validator({lang:'{lang}',effect:'advanced'}) .submit( ajax_form_post );

		//reset hidden-id element
		//Once the ref input is click, the hidden column will be reset
		$(".ajax_form_post").each(function(){ 
			var form  = $(this);
			form.find("[hidden-id]").each(function(){
				input = $(this);
				var refid = input.attr("hidden-id");
				field = $("#" + refid + ""); 
				field.click(function(){ form.data('validator').reset(input)});
				});
			});

		$(".btn_nav").click( btn_nav );
		$(".btn_req").click( btn_req );
		$("button.btn_action").click(ajax_form_button);
		$(".lookup_new").click(function(){
			var url = $(this).attr("url");
			window.open(url,"pselect","scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no");
			return false;
		});

		$(".PmdMultiCheck").one('click',PmdMultiCheck);
		$(".ajax-pmd-remove_attach").one('click',ajax_pmd_remove_attach);

		//At last we will do localize
		$.tools.validator.localize("{lang}", {
			'*'     : "{__('E_ALL')}",
			':email'    : "{__('E_EMAIL')}",
			':number'   : "{__('E_DECIMAL')}",
			':url'      : "{__('E_URL')}",
			'[max]'     : "{__('E_MAX_LENGTH')}",
			'[min]'     : "{__('E_MIN_LENGTH')}",
			'[required]'    : "{__('E_NOT_EMPTY')}",
			});
});

加载中
0
mark35
mark35

$(this).parents('form').data('btn_action',btn_action);
可以优化成

$(this).closest('form').data('btn_action',btn_action);


返回顶部
顶部