jquery.form.js插件实现表单异步提交(文件上传)

阅读更多
近期遇到项目中,一个页面有4个选项卡,8个表单,如果不涉及文件上传,直接用ajax异步提交比较简单,但是偏偏有好几个表单是夹杂了文件上传,传统的异步提交需要分次,比较麻烦。经同学推荐jquery.form.js,实现表单异步提交,简单清爽。

例如(拿其中一个选项卡举例,具体css不予给出)



juqery.form.js异步提交表单实现方法不唯一,这里我用ajaxForm

$(function()
{
 //配置表单异步提交
    $('#educationForm').ajaxForm({
    	beforeSerialize:assembled_education_form,//表单序列化之前处理某些表单控件值,return false 则表单不提交
    	beforeSubmit : validate_education_form,//表单异步提交之前进行表单值合法性验证,return false 则表单不提交
    	success : function(data) {
    		if(data.state == "200")
    		{
//    			alertShow("保存成功");
                //表单提交成功,异步刷新列表
    	    	$.ajax({
    	    		url:"/staffeducation/getlist",
    	    		type:"get",
    	    		data:{staffId:$("#staffId").val()},
    	    		success:function(data)
    	    		{       //模板引擎返回局部页面
    	    			$("#education_table").replaceWith(data);
    	    			$("#staffContent").removeClass("hidden");
    	    	    	        $("#education-info").addClass("hidden");
    	    		}
    	    	});
    		}
    		else
    		{
    			alertShow("保存失败:"+ data.msg);
    		}
    		status = true;
    		$("#educationTime").val("");	//隐藏域不清空,需要手动清空表单
    	},
    	error:function(data){ 
        	status = true;
        	$("#educationTime").val("");	//隐藏域不清空,需要手动清空表单
        },
    	resetForm : true //清空表单
    });
})

function assembled_education_form(form,options)
{
	return true;
}


function validate_education_form(formData, jqForm, options)
{       //防止连续点击,表单重复异步提交
	if(status)
	{
		$("#education_picture").poshytip("hide");
		$("#educationSchool").poshytip("hide");
		$("#educationSchool").poshytip({
			content: '学校不能为空!',
			showOn: 'none',
			alignTo: 'target',
			alignX: 'inner-left',
			offsetX: 0,
			offsetY: 5
		});
		$("#educationMajor").poshytip("hide");
		$("#educationMajor").poshytip({
			content: '专业不能为空!',
			showOn: 'none',
			alignTo: 'target',
			alignX: 'inner-left',
			offsetX: 0,
			offsetY: 5
		});
		
		$("#educationTime").prev().find("input").poshytip("hide");
		$("#educationTime").prev().find("input").poshytip({
			content: '日期不能为空!',
			showOn: 'none',
			alignTo: 'target',
			alignX: 'inner-left',
			offsetX: 0,
			offsetY: 5
		});
		
		status = false;
		
		var flag = true;
		for(var i in formData)
		{
			switch (formData[i].name)
			{
				case "educationSchool":
				{
					if($.trim(formData[i].value) == "")
					{
						flag = false;
						$("#educationSchool").poshytip("show");
					}
					else
					{
						$("#educationSchool").poshytip("hide");
					}
					break;
				} 
				case "educationMajor":
				{
					if($.trim(formData[i].value) == "")
					{
						flag = false;
						$("#educationMajor").poshytip("show");
					}
					else
					{
						$("#educationMajor").poshytip("hide");
					}
					break;
				}
				case "educationTime":
				{
					if($.trim(formData[i].value) == "")
					{
						flag = false;
						$("#educationTime").prev().find("input").poshytip("show");
					}
					else
					{
						$("#educationTime").prev().find("input").poshytip("hide");
					}
					break;
				}
			}
		}
    if(!flag)
        status = true;
		return flag;
	}
	
	return false;
	
}



后台springMVC代码
/**
 * 添加or修改 add 
 * author chensg 
 * 2016.03.15
 */
@RequestMapping(value = "/addorset", method = RequestMethod.POST)
public @ResponseBody RestResult addOrSetStaff(StaffEducation staffEducation,@RequestParam(value = "img" ,required=false) MultipartFile file,HttpServletRequest request,  Model model) {
	if(null == staffEducation.getEducationIsHigh())	//如果没有勾选最高学历,后台不会接受到参数
		staffEducation.setEducationIsHigh(0);
		
	RestResult result = null;
	String educationId ;
	//没有educationId则是新增
	if(null==staffEducation.getEducationId() || "".equals(staffEducation.getEducationId())){
		result =  client.addStaffEducation(staffEducation);
                //获得新增后的唯一uuid
		educationId = result.getResults().get("educationId").toString();
	}else{
		//修改
		result =  client.setStaffEducation(staffEducation);
		educationId = staffEducation.getEducationId();
	}
		
	if( null != file)
	{
                //图片路径用唯一的educationId(uuid)
		String path = request.getSession().getServletContext().getRealPath("upload/"+educationId);
	        String fileName ="educationPicture."+ file.getOriginalFilename().split("\\.")[1];
	        File targetFile = new File(path, fileName);
	        if(!targetFile.exists()){
	            targetFile.mkdirs();
	        }
	        
	        //保存图片路径
	        try {
		            file.transferTo(targetFile);
		            staffEducation = new StaffEducation();
		            staffEducation.setEducationId(educationId);
		            staffEducation.setEducationUrl(request.getContextPath()+"/upload/"+educationId+"/"+fileName);
		            return client.setStaffEducation(staffEducation);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
		}
		
		return result;
	}

你可能感兴趣的:(表单)