最近博主又去研究文件上传了
这次的文件上传是通过ajax上传文件。(看了下ajaxupfileload.js,主要是通过 iframe 提交的数据。)
需求就是在新增用户的时候通过异步上传表单和图片, 功能如图所示:
参考资料:
1.http://blog.csdn.net/zwx19921215/article/details/44133113
2.http://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html
系列文章
1.http://cqjava.iteye.com/blog/2048233
2.http://cqjava.iteye.com/blog/2053119
3.http://cqjava.iteye.com/blog/2058912
最终历经了千辛万苦终于研究了出来,主要用到了 ajaxupfileload.js 插件。
ajaxupfileload.js 提交数据的时候需要以JSON格式提交表单数据,由于原生的 javaScript,Jquery 不支持将表单数据转换成JSON格式的数据,博主又用了另一个插件,将表单数据转换为JSON格式进行提交。
ajaxupfileload.js 里面需要用到 JQuery.handleError 函数,该函数在JQuery高版本中被移除了,我将其放到 ajaxupfileload.js,作为jquery的扩展函数
主要用到的插件下载地址 http://pan.baidu.com/s/1slnAdMt
1.异步提交数据 ajaxupfileload.js
2.将表单转换为JSON formToJson.js
主要步骤
1.将表单数据转换为JSON格式
2.利用ajaxupfileload.js 将数据异步提交到服务器上
3.后台接收数据并处理 参考文章 SpringMVC后台接收数据 http://blog.csdn.net/u010003835/article/details/51000077
前端js --- 通过js提交数据
ajaxupfileload + 表单转JSON
/*添加或者更新结果*/ function saveOrUpdateForm(){ var checkImageFlag = checkImageFileType(); //校验图片是否是正确的格式 var flag = $("#addOrUpdateModalForm").validationAjax(); //对表单数据的校验 flag = checkImageFlag && flag; //alert(flag); if(flag){ var postUrl = appCtx+"userInfo/insertOrUpdate.do"; var params = $("#addOrUpdateModalForm").serializeJson(); //将表单数据转换为JSON //alert(params.name); $("#loading").modal("show"); function ajaxFileUpload() { $.ajaxFileUpload ( { url: postUrl, //用于文件上传的服务器端请求地址 secureuri: false, //是否需要安全协议,一般设置为false fileElementId: 'userImage', //文件上传域的ID dataType: 'json', //返回值类型 一般设置为json data: params, //需要传递JSON对象如这种 {'name':'hahah'} success: function (data, status) //服务器成功响应处理函数 { //alert('上传成功'); }, error: function (data, status, e)//服务器响应失败处理函数 { //alert(e); doSuccess(); //成功后,模态框的状态 successModalStatus(oneRowModalCloseBtn,oneRowModalSaveBtn,oneRowModalUpdateBtn,oneRowModal,oneRowModalTitle,oneRowModalBody); //成功后,刷新表单 succesListFormReflush(); } } ) return false; } ajaxFileUpload(); //将头像和表单数据同时上传 $("#loading").modal("hide"); } }
由于需要上传图片,前端对于图片的校验:
/*校验上传文件的数据类型,前端校验,检查文件的文件类型*/ function checkImageFileType(){ var correctType = new Array("png","jpeg","gif","jpg","bmp"); //正确的图片格式 var oldImageUrl = $("#imageUrl").get(0).value; var fileName = $("#userImage").get(0).value; //如果是之前有图片,现在不上传新图片,不需要校验 if((oldImageUrl!=null||oldImageUrl!="")&&(fileName==null||fileName=="")){ return true; } //对上传的图片进行校验 var fileType = fileName.substr(fileName.lastIndexOf(".")+1); var fileTypeLow = fileType.toLowerCase(); //将图片格式的名字转换为小写 for(index in correctType){ if(fileTypeLow == correctType[index]){ //alert("正确的图片格式"); return true; } } //错误信息的提示 var infoParent = document.getElementById("checkImageInformation"); var tips = document.createElement("div"); tips.id = "checkImageTypeTips"; tips.style.width = "200px"; tips.style.color = "red"; tips.innerHTML = "数据类型不满足要求,请上传 png,jpeg,gif,jpg,bmp类型的图片"; infoParent.appendChild(tips); return false; }
前端页面 + 后台接收部分, 写的很烂,仅作为参考
前端页面
<%@ page contentType="text/html;charset=UTF-8"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%-- <script type="text/javascript" src="<%=request.getContextPath() %>/resources/js/jquery-1.4.4.min.js"></script> --%> <!-- <script type="text/javascript"> $(function(){ $.ajax({ async: false, type: "post", url: appCtx+"userInfo/selectDepartmentTree.do", success : function(data){ alert(data); var msg = eval("("+data+")"); for(var i=0;i<msg.length;i++){ $("#departmentId").append("<option value="+msg[i].id+">"+msg[i].name+"</option>"); } } }); }) </script> --> <form:form id="addOrUpdateModalForm" method="post" modelAttribute="userInfo" enctype="multipart/form-data"> <form:hidden path="userId" data-id="userId" /> <form:hidden path="imageUrl" data-id="imageUrl" /> <div class="content-modal" style="width:620px;"> <div style="width:309px;height:665px;border-right:1px solid #ccc;float:left;"> <h4 style="height:30px;line-height:30px;padding:0px;margin:0px;text-align:center;">上传头像</h4> <p> <label style="display:block;line-height:30px;">当前头像:</label> <br> <%-- <c:if test=" ${empty userInfo.imageUrl} "> --%> <c:if test="${not empty userInfo.imageUrl}"> <span style="width: 150px;height:150px;border:2px solid #ccc;display:inline-block;margin-left: 80px;overflow:hidden;"> <a> <img src="<%=request.getContextPath()%>/resources/images/userImage/${userInfo.imageUrl}"> </a> </span> </c:if> <c:if test="${empty userInfo.imageUrl}"> <span style="width: 150px;height:150px;border:2px solid #ccc;display:inline-block;margin-left: 80px;overflow:hidden;"> <a> <img src="<%=request.getContextPath()%>/resources/images/unknownmale.jpg"> </a> </span> </c:if> </p> <input type="file" id="userImage" name="userImage" style="display:none;" onchange="upfileName.value=this.value" accept="image/x-png,image/gif,image/jpeg,image/bmp"/> <span style="height:50px;line-height:50px; /*清理浮动*/overflow:auto; zoom:1; "> <input type="text" id="upfileName" readonly="readonly" style="float:left; width:220px;"/> <input type="button" onclick="userImage.click()" style="float:left; margin-left:5px; height:23px; width:57px; background: url(<%=request.getContextPath() %>/resources/images/sc.png) no-repeat;border:none;"/> </span> <div id="checkImageInformation"></div> </div> <div style="width:310px; float:left;"> <!-- <div class="input-append"> <input class="input-medium" id="citySel" readonly type="text" value=""> <a id="menuBtn" class="btn" type="button"><i class="icon-search"></i></a> </div> <div id="DropdownMenuBackground" style="display:none; position:absolute;z-index:999;height:300px; min-width:163px; background-color:white;border:1px solid;overflow-y:auto;overflow-x:auto;"> <ul id="dropdownMenu" class="tree"></ul> </div> --> <div class="row-modal"> <div class="control-group-modal"> <label class="control-label" for="organizationId">机构名称:</label> <div class="controls"> <c:if test="${role == 'sys' }"> <form:input disabled="true" data-id="organization" path="organizationId" cssClass="selectText" check-type="required" required-message="请选择机构名称!"/> <%-- <form:select data-id="organization" path="organizationId" cssClass="selectText" onchange="onchangeTree();" check-type="required" required-message="请选择机构名称!"> <form:option value="" >请选择</form:option> <c:forEach var="o" items="${organization }"> <form:option value="${o.organizationId }">${o.companyName }</form:option> </c:forEach> </form:select> --%> <font class="red">*</font> </c:if> <c:if test="${role == 'org' }"> <div class="controls"> <form:input data-id="companyName" path="companyName" readonly="true" cssClass="inputText" style="color:#8C8C8C"/> </div> </c:if> </div> </div> </div> <div class="row-modal"> <div class="control-group-modal"> <label class="control-label" for="name">姓名:</label> <div class="controls"> <form:input data-id="name" path="name" cssClass="inputText" check-type="required maxLength" max-length="10" required-message="请输入员工姓名!" maxLength-message="员工姓名最多5个汉子!" /> <font class="red">*</font> </div> </div> </div> <div class="row-modal"> <div class="control-group-modal"> <label class="control-label" for="employNum">员工工号:</label> <div class="controls"> <form:input data-id="employNum" path="employNum" cssClass="inputText" check-type="required number maxLength" max-length="10" number-message="员工工号为纯数字!" required-message="员工工号不能为空!" maxLength-message="员工工号最多10位数字!" /> <font class="red">*</font> </div> </div> </div> <div class="row-modal"> <div class="control-group-modal"> <label class="control-label" for="sex">性别:</label> <div class="controls"> <form:select data-id="userInfo" path="sex" cssClass="selectText"> <form:option value="">请选择</form:option> <form:option value="1">男</form:option> <form:option value="2">女</form:option> </form:select> </div> </div> </div> <div class="row-modal"> <div class="control-group-modal"> <label class="control-label" for="birthday">生日:</label> <div class="controls"> <form:input data-id="birthday" path="birthday" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})" cssClass="inputText"/> </div> </div> </div> <div class="row-modal"> <div class="control-group-modal"> <label class="control-label" for="card">身份证号:</label> <div class="controls"> <form:input data-id="card" path="card" cssClass="inputText"/> </div> </div> </div> <div class="row-modal"> <div class="control-group-modal"> <label class="control-label" for="departmentId">所属部门:</label> <form:select data-id="departmentId" path="departmentId" cssClass="selectText" check-type="required" required-message="岗位不能为空!"> <form:option value="000" >请选择</form:option> <c:forEach items="${tree}" var="p"> <form:option value="${p.id }">${p.name}</form:option> </c:forEach> </form:select> </div> </div> <div class="row-modal"> <div class="control-group-modal"> <label class="control-label" for="positionId">职务/岗位:</label> <form:select data-id="position" path="positionId" cssClass="selectText" check-type="required" required-message="岗位不能为空!"> <form:option value="000" >请选择</form:option> <c:forEach var="p" items="${position }"> <form:option value="${p.positionId }">${p.positionName }</form:option> </c:forEach> </form:select> </div> </div> <div class="row-modal"> <div class="control-group-modal"> <label class="control-label" for="iphone">手机号:</label> <c:if test="${operation == 'add' }"> <div class="controls"> <form:input data-id="iphone" onkeyup="checkLoginName(this.value)" path="iphone" cssClass="inputText" check-type="mobilePhone required number" /> <font color="red">*</font> <span id="checkIphone"></span> </div> </c:if> <c:if test="${operation == 'modify' }"> <div class="controls"> <form:input data-id="iphone" path="iphone" readonly="true" cssClass="inputText" style="color:#8C8C8C"/> </div> </c:if> </div> </div> <div class="row-modal"> <div class="control-group-modal"> <label class="control-label" for="email">邮箱:</label> <div class="controls"> <form:input data-id="email" path="email" cssClass="inputText" check-type="mail" mail-message="邮箱地址输入有误!" /> <br> </div> </div> </div> <div class="row-modal"> <div class="control-group-modal"> <label class="control-label" for="wechat">微信号:</label> <div class="controls"> <form:input data-id="wechat" path="wechat" cssClass="inputText"/> </div> </div> </div> <div class="row-modal"> <div class="control-group-modal"> <label class="control-label" for="entryDate">入职时间:</label> <div class="controls"> <form:input data-id="entryDate" path="entryDate" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})" cssClass="inputText"/> </div> </div> </div> <div class="row-modal"> <div class="control-group-modal"> <label class="control-label" for="formalizationDate">转正时间:</label> <div class="controls"> <form:input data-id="formalizationDate" path="formalizationDate" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})" cssClass="inputText"/> </div> </div> </div> <div class="row-modal"> <div class="control-group-modal"> <label class="control-label" for="cardNum">卡号:</label> <div class="controls"> <form:input data-id="cardNum" path="cardNum" cssClass="inputText"/> </div> </div> </div> <div class="row-modal"> <div class="control-group-modal"> <label class="control-label" for="remarks">备注/情况:</label> <div class="controls"> <form:textarea rows="5" maxlength="200" data-id="remarks" path="remarks" cssClass="textareaText" /> </div> </div> </div> </div> </div> </form:form>
后台controller
/** * * @作者:szh * @创建时间:2016年3月18日 * @方法功能:添加和修改 */ @RequestMapping("insertOrUpdate") @ResponseBody public ActionResult insertOrUpdate(UserInfo userInfo, HttpSession session, HttpServletRequest request, HttpServletRequest response, @RequestParam(value="userImage",required=false)MultipartFile userImage) { // 定义结果模态框 ActionResult result = new ActionResult(); try { Object obj = session.getAttribute(ConstantAdmin.SESSION_ADMIN_INFO); // 判断userId 为null是 添加|不为null是修改 if (userInfo.getUserId() == null) { if (obj instanceof UserOrganization) { // 将session对象转为organization类型 UserOrganization userOrg = (UserOrganization) obj; // 给员工设置organizationId userInfo.setOrganizationId(userOrg.getOrganizationId()); userInfo.setLastUpdateBy(userOrg.getCompanyName()); userInfo.setUserUuid(UUIDUtil.getUUID()); userInfo.setPassword("123456"); //用户上传头像 String path = request.getSession().getServletContext().getRealPath("/resources/images/userImage"); //文件在服务器上存储的位置 String originFileName = userImage.getOriginalFilename(); //获取原始文件的名字 //System.out.println(originFileName); //上传文件的名字 String type = originFileName.substring(originFileName.lastIndexOf(".")+1); //获取文件的类型,以最后一个"."标识的文件类型作为标准 //System.out.println(type); String fileName = System.currentTimeMillis() + "." + type; //设置新文件的名字 if((!(type==null)) && (!(type.equals("")))) //确实上传了文件 { File targetFile = new File(path, fileName); //在指定路径创建一个文件 try { userImage.transferTo(targetFile); //将文件保存到服务器上指定的路径上 userInfo.setImageUrl(fileName); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } userInfoService.insertSelective(userInfo); // 日志记录 Logger logger = Logger.getLogger(this.getClass()); MDC.put("adminId", userOrg.getOrganizationId()); MDC.put("adminType", "2"); MDC.put("logType", TypeModel.LogType.LOG_SYS); logger.info("企业管理员(" + ((UserOrganization) obj).getCompanyName() + ")新增员工信息成功!"); } else if (obj instanceof SysUser) { userInfo.setLastUpdateBy(((SysUser) obj).getLoginName()); userInfoService.insertSelective(userInfo); } // 用户岗位中间表对象 UserPositionRel positionRel = new UserPositionRel(); // 设置userId positionRel.setUserId(userInfo.getUserId()); // 查询该user是否已存在岗位 List<HashMap<String, Object>> list = userPositionService.selectUserPositionRel(positionRel); if (list.size() == 0) { // 设置新岗位id positionRel.setPositionId(userInfo.getPositionId()); // 未被分配岗位则直接进行分配(插入) userPositionService.insertUserPositionRel(positionRel); } else { // 已被分配岗位则删除中间表中已有的岗位 userPositionService.deleteUserPositionRel(Integer.toString(userInfo.getUserId())); // 设置新岗位id positionRel.setPositionId(userInfo.getPositionId()); // 将新岗位插入中间表 userPositionService.insertUserPositionRel(positionRel); } result.setResult(OPERATOR_RESULT_SUCCESS_KEY); result.setMessage(OPERATOR_RESULT_SUCCESS_ADD_VALUE); // 更新 } else { // 用户和岗位中间表对象 UserPositionRel positionRel = new UserPositionRel(); // 设置userId positionRel.setUserId(userInfo.getUserId()); // 查询该用户是否已被分配岗位 List<HashMap<String, Object>> list = userPositionService.selectUserPositionRel(positionRel); // size==0 该角色未被分配岗位 反之已被分配岗位 if (list.size() == 0) { // 设置新岗位id positionRel.setPositionId(userInfo.getPositionId()); // 未被分配岗位则直接进行分配(插入) userPositionService.insertUserPositionRel(positionRel); } else { // 已被分配岗位则删除中间表中已有的岗位 userPositionService.deleteUserPositionRel(Integer.toString(userInfo.getUserId())); // 设置新岗位id positionRel.setPositionId(userInfo.getPositionId()); // 将新岗位插入中间表 userPositionService.insertUserPositionRel(positionRel); } String path = request.getSession().getServletContext().getRealPath("/resources/images/userImage"); //文件在服务器上存储的位置 //修改用户上传的头像 //删除原有的头像,需查询原有图片名字 //用户上传头像 UserInfo oldUserInfo = userInfoService.selectByPrimaryKey(String.valueOf(userInfo.getUserId())); String oldImageUrl = oldUserInfo.getImageUrl(); //删除旧文件 //如果与原来头像是一个图片 String currentImageUrl = userInfo.getImageUrl(); if(currentImageUrl!=null && (!(oldImageUrl==null || oldImageUrl.equals(""))) && currentImageUrl.equals(oldImageUrl)){ //用户没上传新图像 不做任何操作 } else{ //如果原头像存在,则删除原头像,有可能有冗余数据 File oldFile = new File(path+File.separator+oldImageUrl); if(oldFile.exists() && oldFile.isFile()){ oldFile.delete(); } //存储新上传的头像 String originFileName = userImage.getOriginalFilename(); //获取原始文件的名字 String type = originFileName.substring(originFileName.lastIndexOf(".")+1); //获取文件的类型,以最后一个"."标识的文件类型作为标准 String fileName = System.currentTimeMillis() + "." + type; //设置新文件的名字 File targetFile = new File(path, fileName); //在指定路径创建一个文件 try { userImage.transferTo(targetFile); //将文件保存到服务器上指定的路径上 userInfo.setImageUrl(fileName); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } if (obj instanceof UserOrganization) { // 将session对象转为organization类型 UserOrganization userOrg = (UserOrganization) obj; userInfo.setLastUpdateBy(userOrg.getCompanyName()); userInfoService.updateByPrimaryKeySelective(userInfo); // 日志记录 Logger logger = Logger.getLogger(this.getClass()); MDC.put("adminId", userOrg.getOrganizationId()); MDC.put("adminType", "2"); MDC.put("logType", TypeModel.LogType.LOG_SYS); logger.info("企业管理员(" + ((UserOrganization) obj).getCompanyName() + ")修改员工信息成功!"); } else if (obj instanceof SysUser) { userInfo.setLastUpdateBy(((SysUser) obj).getLoginName()); userInfoService.updateByPrimaryKeySelective(userInfo); // 日志记录 Logger logger = Logger.getLogger(this.getClass()); MDC.put("adminId", ((SysUser) obj).getId()); MDC.put("adminType", "1"); MDC.put("logType", TypeModel.LogType.LOG_SYS); logger.info("后台管理员(" + ((SysUser) obj).getLoginName() + ")修改员工信息成功!"); } result.setResult(OPERATOR_RESULT_SUCCESS_KEY); result.setMessage(OPERATOR_RESULT_SUCCESS_UPDATE_VALUE); } } catch (Exception e) { e.printStackTrace(); result.setResult(OPERATOR_RESULT_ERROR_KEY); result.setMessage(OPERATOR_RESULT_ERROR_VALUE); } // 返回结果 return result; }
插件的源码
1.ajaxupfileload.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 = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; if(window.ActiveXObject) { if(typeof uri== 'boolean'){ iframeHtml += ' src="' + 'javascript:false' + '"'; } else if(typeof uri== 'string'){ iframeHtml += ' src="' + uri + '"'; } } 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('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); if(data) { for(var i in data) { jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').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" ) eval( "data = " + data ); // evaluate scripts within html if ( type == "html" ) jQuery("<div>").html(data).evalScripts(); return data; } });
2.formToJson.js
$.fn.serializeJson=function(){ var serializeObj={}; var array=this.serializeArray(); var str=this.serialize(); $(array).each(function(){ if(serializeObj[this.name]){ if($.isArray(serializeObj[this.name])){ serializeObj[this.name].push(this.value); }else{ serializeObj[this.name]=[serializeObj[this.name],this.value]; } }else{ serializeObj[this.name]=this.value; } }); return serializeObj; };