首页 > 编程语言 >深入学习jquery源码之序列化表单

深入学习jquery源码之序列化表单

时间:2023-02-23 22:04:14浏览次数:58  
标签:jquery function null return name 源码 var 序列化 String


深入学习jquery源码之序列化表单

serialize()

概述

序列表表格内容为字符串。

序列表表格内容为字符串,用于 Ajax 请求。

<p id="results"><b>Results: </b> </p>
<form>
<select name="single">
<option>Single</option>
<option>Single2</option>
</select>
<select name="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select><br/>
<input type="checkbox" name="check" value="check1"/> check1
<input type="checkbox" name="check" value="check2" checked="checked"/> check2
<input type="radio" name="radio" value="radio1" checked="checked"/> radio1
<input type="radio" name="radio" value="radio2"/> radio2
</form>
$("#results").append( "<tt>" + $("form").serialize() + "</tt>" );
var paras = $submit_form.serialize();
$.post(url, paras, function (data) {
if (data.code == 0) {
if(data.data != null) {
key = data.data["trainId"];
$("input[name='trainId']").val(key);
}
$Core.UI.message.success("保存成功!");
//关闭窗口
$('#btnquery', parent.document).click();
}
else {
$Core.UI.message.error(data.msg);
}
});

深入学习jquery源码之序列化表单_JSON

深入学习jquery源码之序列化表单_jQuery_02

 

 

serializeArray()

概述

序列化表格元素 (类似 '.serialize()' 方法) 返回 JSON 数据结构数据。

'''注意''',此方法返回的是JSON对象而非JSON字符串。需要使用插件或者第三方库进行字符串化操作。

返回的JSON对象是由一个对象数组组成的,其中每个对象包含一个或两个名值对——name参数和value参数(如果value不为空的话)。举例来说:

[ 
{name: 'firstname', value: 'Hello'},
{name: 'lastname', value: 'World'},
{name: 'alias'}, // this one was empty
]

取得表单内容并插入到网页中。

<p id="results"><b>Results:</b> </p>
<form>
<select name="single">
<option>Single</option>
<option>Single2</option>
</select>
<select name="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select><br/>
<input type="checkbox" name="check" value="check1"/> check1
<input type="checkbox" name="check" value="check2" checked="checked"/> check2
<input type="radio" name="radio" value="radio1" checked="checked"/> radio1
<input type="radio" name="radio" value="radio2"/> radio2
</form>
var fields = $("select, :radio").serializeArray();
jQuery.each( fields, function(i, field){
$("#results").append(field.value + " ");
});

 

序列化表单

-----------------前台序列化表单封装数据JSON.stringify----------------------
$("#btnAdd").click(function () {
if ($submit_form.form("validate")) {
var url = add_url;
if (key){
url = upd_url;
}
var paras = $submit_form.serializeArray();
var rows2 = $("#dglist2").gridsub("getRows");
var p2 = [];
var flag=true;
$.each(rows2, function (k, j) {
var temp2 = { deviceId: j.deviceId, deviceName: j.deviceName, deviceNumber: j.deviceNumber, assetsNumber: j.assetsNumber, deviceSpec: j.deviceSpec, propertyAscription: j.propertyAscription, company: j.company, number: j.number, installMoney: j.installMoney, total: j.total, installCheckId: key,unitMoney:j.unitMoney,manufacturer:j.manufacturer};

p2.push(temp2);
});
paras.push({ 'name': "acceptdetails", value: JSON.stringify(p2) });
if(flag){
$("#btnSave").attr("disabled", "disabled");
$.post(url, paras, function (data) {
$("#btnAdd").removeAttr("disabled");
if (data.code == 0) {
/*$Core.UI.message.success("操作成功!");
$('#btnAdd').attr('disabled',"true");*/

if(data.data != null) {
key = data.data["deviceInstallCheckId"];
$("input[name='deviceInstallCheckId']").val(key);
}
$Core.UI.message.success("保存成功!");
//关闭窗口
/* $('.panel-tool-close', parent.document).each(function (j, k) {
k.click();//这样是关闭所以窗口
});*/
$('#btnquery', parent.document).click();

}
else {
$Core.UI.message.error(data.msg);
}
});
}

}
});

-------------------------后台接收数据并解析--------------------------------
@Override
public InstallCheck auditedThreePublicUser(InstallCheck installCheck, String acceptdetails,SessionData currUserData) {
// TODO Auto-generated method stub
if ("6".equals(installCheck.getApproveState())) {
//审批通过

//获取序列化的数据插入到se_install_check_item
if(StringUtil.isNotEmpty(acceptdetails)) {
List<InstallCheckItem> installCheckItems = JSONArray.parseArray(acceptdetails, InstallCheckItem.class);
for (InstallCheckItem detail : installCheckItems) {
installCheckItemMapper.updateByPrimaryKeySelective(detail);
}
}
}

深入学习jquery源码之序列化表单_字符串_03

深入学习jquery源码之序列化表单_jQuery_04

深入学习jquery源码之序列化表单_jQuery_05

深入学习jquery源码之序列化表单_JSON_06

p2

深入学习jquery源码之序列化表单_字符串_07

JSON.stringify(p2) 变为json串

深入学习jquery源码之序列化表单_jQuery_08

深入学习jquery源码之序列化表单_字符串_09

深入学习jquery源码之序列化表单_jQuery_10

深入学习jquery源码之序列化表单_JSON_11

[{"deviceId":null,"deviceName":"3,mon","deviceNumber":"分隔","assetsNumber":"大锅饭","deviceSpec":"dhd","propertyAscription":"2","company":"发动","number":213,"installMoney":321,"total":14,"installCheckId":"12","unitMoney":312,"manufacturer":"给对方22"},{"deviceId":"","deviceName":"2,assis","deviceNumber":"发生","assetsNumber":"发生","deviceSpec":"as","propertyAscription":"1","company":"请问","number":"123","installMoney":"41","total":"312","installCheckId":"12","unitMoney":"41","manufacturer":"阿发"}]

jsonArray.parseArray()

 

 

 

jQuery.parseJSON(json)

概述

接受一个JSON字符串,返回解析后的对象。

传入一个畸形的JSON字符串会抛出一个异常。比如下面的都是畸形的JSON字符串:

  • {test: 1} ( test 没有包围双引号)
  • {'test': 1} (使用了单引号而不是双引号)

另外,如果你什么都不传入,或者一个空字符串、null或undefined,parseJSON都会返回 null 。

参数

json String

要解析的JSON字符串

解析一个JSON字符串

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
var cookieuser;
try {
cookieuser = $.parseJSON(cookieData);
} catch (e) {
//window.location.href = TIMEOUT_PATH;
return {};
}

深入学习jquery源码之序列化表单_JSON_12

深入学习jquery源码之序列化表单_字符串_13

 

jQuery.parseXML(data)

概述

解析一个字符串到一个XML文件。

jQuery.parseXML使用原生解析函数浏览器创建一个有效的XML文档。这文档可以被传递给jQuery创建一个典型的jQuery对象,可以查询及操作。

参数

data 

用来解析的格式良好的XML字符串。

创建一个jQuery对象使用一个XML字符串并得到标题节点的值。:

var xml = '<rss version="2.0"><channel><title>RSS Title</title></channel></rss>',
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$title = $xml.find( 'title' ); // append "RSS Title" to #someElement
$( '#someElement' ).append( $title.text() ); // change the title to "XML Title"
$title.text( 'XML Title' ); // append "XML Title" to #anotherElement
$( '#anotherElement' ).append( $title.text() );

 

jquery源码

var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;

function buildParams(prefix, obj, traditional, add) {
var name;

if (jQuery.isArray(obj)) {
// Serialize array item.
jQuery.each(obj, function (i, v) {
if (traditional || rbracket.test(prefix)) {
// Treat each array item as a scalar.
add(prefix, v);

} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams(prefix + "[" + (typeof v === "object" ? i : "") + "]", v, traditional, add);
}
});

} else if (!traditional && jQuery.type(obj) === "object") {
// Serialize object item.
for (name in obj) {
buildParams(prefix + "[" + name + "]", obj[name], traditional, add);
}

} else {
// Serialize scalar item.
add(prefix, obj);
}
}

// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function (a, traditional) {
var prefix,
s = [],
add = function (key, value) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction(value) ? value() : (value == null ? "" : value);
s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
};

// Set traditional to true for jQuery <= 1.3.2 behavior.
if (traditional === undefined) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}

// If an array was passed in, assume that it is an array of form elements.
if (jQuery.isArray(a) || (a.jquery && !jQuery.isPlainObject(a))) {
// Serialize the form elements
jQuery.each(a, function () {
add(this.name, this.value);
});

} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for (prefix in a) {
buildParams(prefix, a[prefix], traditional, add);
}
}

// Return the resulting serialization
return s.join("&").replace(r20, "+");
};

jQuery.fn.extend({
serialize: function () {
return jQuery.param(this.serializeArray());
},
serializeArray: function () {
return this.map(function () {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop(this, "elements");
return elements ? jQuery.makeArray(elements) : this;
})
.filter(function () {
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery(this).is(":disabled") &&
rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) &&
(this.checked || !rcheckableType.test(type));
})
.map(function (i, elem) {
var val = jQuery(this).val();

return val == null ?
null :
jQuery.isArray(val) ?
jQuery.map(val, function (val) {
return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
}) :
{ name: elem.name, value: val.replace(rCRLF, "\r\n") };
}).get();
}
});



var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;

jQuery.parseJSON = function (data) {
// Attempt to parse using the native JSON parser first
if (window.JSON && window.JSON.parse) {
// Support: Android 2.3
// Workaround failure to string-cast null input
return window.JSON.parse(data + "");
}

var requireNonComma,
depth = null,
str = jQuery.trim(data + "");

// Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
// after removing valid tokens
return str && !jQuery.trim(str.replace(rvalidtokens, function (token, comma, open, close) {

// Force termination if we see a misplaced comma
if (requireNonComma && comma) {
depth = 0;
}

// Perform no more replacements after returning to outermost depth
if (depth === 0) {
return token;
}

// Commas must not follow "[", "{", or ","
requireNonComma = open || comma;

// Determine new depth
// array/object open ("[" or "{"): depth += true - false (increment)
// array/object close ("]" or "}"): depth += false - true (decrement)
// other cases ("," or primitive): depth += true - true (numeric cast)
depth += !close - !open;

// Remove this token
return "";
})) ?
(Function("return " + str))() :
jQuery.error("Invalid JSON: " + data);
};


// Cross-browser xml parsing
jQuery.parseXML = function (data) {
var xml, tmp;
if (!data || typeof data !== "string") {
return null;
}
try {
if (window.DOMParser) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString(data, "text/xml");
} else { // IE
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = "false";
xml.loadXML(data);
}
} catch (e) {
xml = undefined;
}
if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) {
jQuery.error("Invalid XML: " + data);
}
return xml;
};

 

 

自定义序列化插件

serializeObject

$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};

$("#btnSave").click(function () {
if ($("#submit_form").form("validate")) {
var url = "security/add";
if ($("#id").val() != "")
url = "security/upd";
var paras = {
list:[],
publicServicesUser:{}
};
paras.publicServicesUser = $("#submit_form").serializeObject();

for (var i= 13;i <= index; i++) {
var obj = {
contactsType: "",
contactsName:"",
contactsPhone:""
};
var row = $("#submit_table tr:eq(" + i + ")");
obj.contId = row.find("#contId").val();
obj.contactsType = row.find("#contactsType").combo("getValue");
obj.contactsName = row.find("#contactsName").textbox("getValue");
obj.contactsPhone = row.find("#contactsPhone").textbox("getValue");
paras.list.push(obj)
}
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(paras),
dataType: "json",
success: function (message) {
if (message.code == 0) {
$Core.UI.message.success(message.msg);
}else{
$Core.UI.message.warning(message.msg);
}
}
});
}
});

深入学习jquery源码之序列化表单_jQuery_14

后台

import com.alibaba.fastjson.JSONArray;

@PostMapping("upd")
public AssembleJSON update(@RequestBody UserContacts userContacts) {
PublicServicesUser publicServicesUser = userContacts.getPublicServicesUser();

SessionData sessionData =getCurrUserData();

publicServicesUser.setUpdateUser(sessionData.getUserId());
publicServicesUser.setUpdateUserName(sessionData.getUserName());
if (publicServicesUser.getUpdateTime() == null) {
publicServicesUser.setUpdateTime(new Date());
}

Map<Object, Object> objectObjectMap = MapUtil.object2Map(publicServicesUser);
String str = JSONArray.toJSONString(userContacts.getList());
PublicServicesUserTemp publicServicesUserTemp = MapUtil.map2Object(objectObjectMap, PublicServicesUserTemp.class);
publicServicesUserTemp.setContactsStr(str);
publicServicesUserTemp.setApproveState("0");
publicServicesUserTemp.setUpdateTime(new Date());
publicServicesUserTempService.insert(publicServicesUserTemp);

PublicServicesUser publicServicesUser1 = new PublicServicesUser();
publicServicesUser1.setId(publicServicesUser.getId());
publicServicesUser1.setApproveState("0");
publicServicesUser1.setUpdateTime(new Date());
userContacts.setPublicServicesUser(publicServicesUser1);
userContacts.setList(null);
return AssembleJSON.SUCCESS(userContactsService.updateContactsSelective(userContacts));
}

深入学习jquery源码之序列化表单_jQuery_15

 

.toJSON( )

把数组转换成json类型

//数组里的字段的命名和类型要和一般处理程序里定义的类里的变量要一样
//否则会出问题
var postdata = new Array();
postdata[1] = { id: 1, number: "yes" };
postdata[2] = { id: 2, number: "no" };
var postData = $.toJSON(postdata); //把数组转换成json字符串
//将json字符串反序列化,这个只是测试一下数组是否转换成json字符串
var content = $.parseJSON(postData);
$.each(content, function () {
alert(this.number);
});
querySelectCallbackData = function () {
var idArr = [];
for(i=0,len=codeName.length; i<len; i++){
if(""!=codeName[i]["code"]&&""!=codeName[i]["name"])
{
var obj = {};
obj.code = codeName[i]["code"];
obj.name = codeName[i]["name"];
obj.contact = codeName[i]["contact"];
obj.idNumber = codeName[i]["idNumber"];
idArr.push(obj);
}
}
return idArr;
}

------------------$.toJSON数据封装-------------------
layer.open({
type: this.cardPopStyle,
title: '活动分发',
area: ['95%','90%'],
maxmin: true,
shadeClose: false, //开启遮罩关闭
btn: ['确认', '取消'],
content: this.cardPopStyle == LayuiPopStyle.LAYUI_CONTENT_LAYER ? $.loadHtml(url) : url,
success : function(layero){
layui.form.render();
},
yes:function(index, layero){
var dataArr = window["layui-layer-iframe" + index].querySelectCallbackData();
var sendUrl = CONTEXT_PATH+"/activityMetting/sendActivity"
var params={
userList :$.toJSON(dataArr),
activityId:activityMeetingId[0]
}
var result = $.getData(sendUrl,params);
if(result.status == 1000){
layer.msg("活动分发成功!");
}

},
end: function(){ //销毁列表回调方法
/*layui.table.reload(_self.tableId)*/
$(".layui-laypage-btn")[0].click();
if(_self.closeCard && $.isFunction(_self.closeCard)){
return _self.closeCard();
}
return false;
},
cancel: function(){

}
});

---------------后台接收并解析-----------------------
@RequestMapping("/activityMetting/sendActivity")
@ResponseBody
public AssembleJSON sendActivity(String userList,String activityId,HttpServletRequest request)
{
User user = (User)request.getSession().getAttribute("current_login_user");
List<PartyMemberDto> sendUserList = JSONObject.parseArray(userList,PartyMemberDto.class);
activityMettingService.saveSendActivityInfo(user.getUserId(), activityId, sendUserList);
return AssembleJSON.SUCCESS;
}

删除操作

delBef: function(curDom, event){
var _self = this;
var data = _self.getSelectIds();
if(data.length == 0){
layer.msg("请至少选择一条需要删除的数据");
return;
}
var url = $(curDom).attr("url") + "?act=" + WebConst.DELETE;
layer.confirm('确定删除吗', function(index){
var dataArr = new Array();
var Row = _self.getSelectRows();
for(var i=0;i<Row.length;i++)
{
var adviceData = new Object();
adviceData.adviceFlowId = Row[i].adviceFlowId;
adviceData.companyId = Row[i].companyId;
dataArr.push(adviceData);
}
var checkUrl = CONTEXT_PATH +"/advice/beforeDel"
var param ={
"JsonArray":$.toJSON(dataArr)//把数组转换成json字符串
}
var retData = $.getData(checkUrl,param);
if(retData.status==-1000 ){
return layer.msg("无法进行删除");
return;
}else{
$.ajaxReq(url,$.toJSON(data),function(){
layui.table.reload(_self.tableId)
});
return layer.msg("删除成功");
}
layer.close(index);

});
}
@RequestMapping("/advice/beforeDel")
@ResponseBody
public AssembleJSON beforedeleteAdvice(String JsonArray)
{

List<Advice> adviceList = JSON.parseArray(JsonArray, Advice.class);
for(Advice advice:adviceList) {
String adviceFlowId =advice.getAdviceFlowId();
String companyId = advice.getCompanyId();
AdviceFLowNodeVO upFLowNodeVO = new AdviceFLowNodeVO();
upFLowNodeVO.setAdviceFlowId(adviceFlowId);
upFLowNodeVO.setCompanyId(companyId);
AdviceFLowNodeVO adviceFLowNodeVO = new AdviceFLowNodeVO();
if(null!=adviceFlowId) {
adviceFLowNodeVO = adviceFlowNodeService.getUpAdvice(upFLowNodeVO);
}else {
adviceFLowNodeVO = null;
}
if(null!=adviceFLowNodeVO) {
String status = adviceFLowNodeVO.getAdviceStatus();
if("1".equals(status)||"2".equals(status)) {
return AssembleJSON.FAILURE("已经提交公开不能删除");
}
}
}

return AssembleJSON.SUCCESS;

}

 

Json2插件

JSON.stringify(params)

js对象转json字符串

$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};

$("#btnSave").click(function () {
if ($("#submit_form").form("validate")) {
var url = "security/add";
if ($("#id").val() != "")
url = "security/upd";
var paras = {
list:[],
publicServicesUser:{}
};
paras.publicServicesUser = $("#submit_form").serializeObject();

for (var i= 13;i <= index; i++) {
var obj = {
contactsType: "",
contactsName:"",
contactsPhone:""
};
var row = $("#submit_table tr:eq(" + i + ")");
obj.contId = row.find("#contId").val();
obj.contactsType = row.find("#contactsType").combo("getValue");
obj.contactsName = row.find("#contactsName").textbox("getValue");
obj.contactsPhone = row.find("#contactsPhone").textbox("getValue");
paras.list.push(obj)
}
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(paras),
dataType: "json",
success: function (message) {
if (message.code == 0) {
$Core.UI.message.success(message.msg);
}else{
$Core.UI.message.warning(message.msg);
}
}
});
}
});
import com.alibaba.fastjson.JSONArray;

@PostMapping("upd")
public AssembleJSON update(@RequestBody UserContacts userContacts) {
PublicServicesUser publicServicesUser = userContacts.getPublicServicesUser();

SessionData sessionData =getCurrUserData();

publicServicesUser.setUpdateUser(sessionData.getUserId());
publicServicesUser.setUpdateUserName(sessionData.getUserName());
if (publicServicesUser.getUpdateTime() == null) {
publicServicesUser.setUpdateTime(new Date());
}

Map<Object, Object> objectObjectMap = MapUtil.object2Map(publicServicesUser);
String str = JSONArray.toJSONString(userContacts.getList());
PublicServicesUserTemp publicServicesUserTemp = MapUtil.map2Object(objectObjectMap, PublicServicesUserTemp.class);
publicServicesUserTemp.setContactsStr(str);
publicServicesUserTemp.setApproveState("0");
publicServicesUserTemp.setUpdateTime(new Date());
publicServicesUserTempService.insert(publicServicesUserTemp);

PublicServicesUser publicServicesUser1 = new PublicServicesUser();
publicServicesUser1.setId(publicServicesUser.getId());
publicServicesUser1.setApproveState("0");
publicServicesUser1.setUpdateTime(new Date());
userContacts.setPublicServicesUser(publicServicesUser1);
userContacts.setList(null);
return AssembleJSON.SUCCESS(userContactsService.updateContactsSelective(userContacts));
}

深入学习jquery源码之序列化表单_jQuery_15

深入学习jquery源码之序列化表单_字符串_17

深入学习jquery源码之序列化表单_JSON_18

 

 

JSON.parse() 

将json字符串转换成json对象

深入学习jquery源码之序列化表单_JSON_19

深入学习jquery源码之序列化表单_jQuery_20

深入学习jquery源码之序列化表单_jQuery_21

深入学习jquery源码之序列化表单_jQuery_22

 

Json2插件源码

var JSON;
JSON || (JSON = {}),
function () {
function f(a) {
return a < 10 ? "0" + a : a
}

function quote(a) {
return escapable.lastIndex = 0, escapable.test(a) ? '"' + a.replace(escapable, function (a) {
var b = meta[a];
return typeof b == "string" ? b : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)
}) + '"' : '"' + a + '"'
}

function str(a, b) {
var c, d, e, f, g = gap,
h, i = b[a];
i && typeof i == "object" && typeof i.toJSON == "function" && (i = i.toJSON(a)), typeof rep == "function" && (i = rep.call(b, a, i));
switch (typeof i) {
case "string":
return quote(i);
case "number":
return isFinite(i) ? String(i) : "null";
case "boolean":
case "null":
return String(i);
case "object":
if (!i) return "null";
gap += indent, h = [];
if (Object.prototype.toString.apply(i) === "[object Array]") {
f = i.length;
for (c = 0; c < f; c += 1) h[c] = str(c, i) || "null";
return e = h.length === 0 ? "[]" : gap ? "[\n" + gap + h.join(",\n" + gap) + "\n" + g + "]" : "[" + h.join(",") + "]", gap = g, e
}
if (rep && typeof rep == "object") {
f = rep.length;
for (c = 0; c < f; c += 1) typeof rep[c] == "string" && (d = rep[c], e = str(d, i), e && h.push(quote(d) + (gap ? ": " : ":") + e))
} else
for (d in i) Object.prototype.hasOwnProperty.call(i, d) && (e = str(d, i), e && h.push(quote(d) + (gap ? ": " : ":") + e));
return e = h.length === 0 ? "{}" : gap ? "{\n" + gap + h.join(",\n" + gap) + "\n" + g + "}" : "{" + h.join(",") + "}", gap = g, e
}
}
"use strict", typeof Date.prototype.toJSON != "function" && (Date.prototype.toJSON = function (a) {
return isFinite(this.valueOf()) ? this.getUTCFullYear() + "-" + f(this.getUTCMonth() + 1) + "-" + f(this.getUTCDate()) + "T" + f(this.getUTCHours()) + ":" + f(this.getUTCMinutes()) + ":" + f(this.getUTCSeconds()) + "Z" : null
}, String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (a) {
return this.valueOf()
});
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap, indent, meta = {
"\b": "\\b",
"\t": "\\t",
"\n": "\\n",
"\f": "\\f",
"\r": "\\r",
'"': '\\"',
"\\": "\\\\"
},
rep;
typeof JSON.stringify != "function" && (JSON.stringify = function (a, b, c) {
var d;
gap = "", indent = "";
if (typeof c == "number")
for (d = 0; d < c; d += 1) indent += " ";
else typeof c == "string" && (indent = c);
rep = b;
if (!b || typeof b == "function" || typeof b == "object" && typeof b.length == "number") return str("", {
"": a
});
throw new Error("JSON.stringify")
}), typeof JSON.parse != "function" && (JSON.parse = function (text, reviver) {
function walk(a, b) {
var c, d, e = a[b];
if (e && typeof e == "object")
for (c in e) Object.prototype.hasOwnProperty.call(e, c) && (d = walk(e, c), d !== undefined ? e[c] = d : delete e[c]);
return reviver.call(a, b, e)
}
var j;
text = String(text), cx.lastIndex = 0, cx.test(text) && (text = text.replace(cx, function (a) {
return "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)
}));
if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) return j = eval("(" + text + ")"), typeof reviver == "function" ? walk({
"": j
}, "") : j;
throw new SyntaxError("JSON.parse")
})
}();

 

其他序列化插件

var params = $('#search_form').serializeArray();
$Core.util.QueryFormSerializeArray("search_form")
var v = $Core.util.QueryFormSerializeString('search_form');
paras.querystr = v;

深入学习jquery源码之序列化表单_字符串_23

 

源码

(function (window, $, undefined) {
var _util = function () {
/*
* 序列化Form 返回数组对象
* @param {any} domid domid
*/
this.QueryFormSerializeArray = function (domid) {
var form = null;
if (typeof (domid) === "string")
from = $('#' + domid);
else
from = domid;
var p = from.serializeArray();
var s = $.map(p, function (n) {
var t = $("#" + n.name);
if (t.size() == 0)
t = from.find("*[textboxname='" + n.name + "']");
var query = {};
var s = $.trim(t.attr('data-query'));
if (s) {
if (s.substring(0, 1) != '{') {
s = '{' + s + '}';
}
query = (new Function('return ' + s))();
if (query.filed) {
query.name = query.filed;
//query.remove("filed");
}
}
//console.log(query);
return $.extend({}, n, query);
});

return s;
};
/**
* 序列化Form 返回字符串
* @param {string} domid
* @return {any} 序列化后的
*/
this.QueryFormSerializeString = function (domid) {
var s = this.QueryFormSerializeArray(domid);
var strpars = JSON.stringify(s);
return strpars;
};
};
$Core.util = new _util();
})(window, jQuery);

 

通过jquery.form.js插件序列化表单

serializeJson源码

/**
* DOM操作扩展
*/
$.fn.extend({
/**
* form序列化转json
*/
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;
}
});

html

<script type="text/javascript" src="<%=request.getContextPath() %>/platform/views/cusviews/JKJL_VIEWS/js/jquery.form.js"></script>
<input id="ids" type="hidden" value="<%=request.getParameter("ids") %>"/>
<input id="isRead" type="hidden" value="<%=request.getParameter("isRead") %>"/>
<input id="xcbh" type="hidden" value="<%=request.getParameter("xcbh") %>"/>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<input id="root" type="hidden" value="${ctx }"/>
<form id="paramForm" action="<%=request.getContextPath() %>/Addxctyz" >
<div class="tb_tab">
<div class="tb_col">
<ul>
<li class="on">基本信息</li>
</ul>
</div>

<div class="turn" style="display: block; opacity: 1;">

<div class="tb_query">
<div class="tb_subq">
<label>时间</label>
<input type="text" class="Wdate" onClick="WdatePicker({ dateFmt: 'yyyy-MM-dd HH:mm:ss' })" id="trbrqs" name="xcsj"/>
<!-- <input type="text" id="trbrqs" name="xcsj"/> -->
</div>
<div class="tb_subq">
<label>值班人</label>
<input type="text" id="tzbddys" name="zbddy"/>
</div>
</div>

<div class="tb_table">

<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td width="100">单位</td>
<td colspan="2" class="tt_table" width="*">
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td width="200">站名</td>
<td width="200">运行状况</td>
<td width="*">处理措施</td>
<td width="200">备注</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>一所</td>
<td colspan="2" class="tt_table">
<table cellpadding="0" cellspacing="0" border="0" class="jydx">
<tr>
<td width="200">一所站点A</td>
<td width="200" class="lblxz">
<label><input type="radio" name="1_yz_xz" value="1"/>正常</label>
<label><input type="radio" name="1_yz_xz" value="2"/>不正常</label>
</td>
<td width="*"><input type="text" class="cs" name="1_yz_cs"/></td>
<td width="200"><input type="text" class="bz" name="1_yz_bz"/></td>
</tr>
<tr>
<td>一所站点B</td>
<td>
<label><input type="radio" name="1_tz_xz" value="1"/>正常</label>
<label><input type="radio" name="1_tz_xz" value="2"/>不正常</label>
</td>
<td><input type="text" class="cs" name="1_tz_cs"/></td>
<td><input type="text" class="bz" name="1_tz_bz"/></td>
</tr>
<tr>
<td>一所站点C</td>
<td>
<label><input type="radio" name="1_lq_xz" value="1"/>正常</label>
<label><input type="radio" name="1_lq_xz" value="2"/>不正常</label>
</td>
<td><input type="text" class="cs" name="1_lq_cs"/></td>
<td><input type="text" class="bz" name="1_lq_bz"/></td>
</tr>
<tr>
<td>一所站点D</td>
<td>
<label><input type="radio" name="1_sc_xz" value="1"/>正常</label>
<label><input type="radio" name="1_sc_xz" value="2"/>不正常</label>
</td>
<td><input type="text" class="cs" name="1_sc_cs"/></td>
<td><input type="text" class="bz" name="1_sc_bz"/></td>
</tr>
<tr>
<td>一所站点E</td>
<td>
<label><input type="radio" name="1_mf_xz" value="1"/>正常</label>
<label><input type="radio" name="1_mf_xz" value="2"/>不正常</label>
</td>
<td><input type="text" class="cs" name="1_mf_cs"/></td>
<td><input type="text" class="bz" name="1_mf_bz"/></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>二所</td>
<td colspan="2" class="tt_table">
<table cellpadding="0" cellspacing="0" border="0" class="jydx">
<tr>
<td width="200">二所站点A</td>
<td width="200">
<label><input type="radio" name="2_tzz_xz" value="1"/>正常</label>
<label><input type="radio" name="2_tzz_xz" value="2"/>不正常</label>
</td>
<td width="*"><input type="text" class="cs" name="2_tzz_cs"/></td>
<td width="200"><input type="text" class="bz" name="2_tzz_bz"/></td>
</tr>
<tr>
<td>二所站点B</td>
<td>
<label><input type="radio" name="2_jcl_xz" value="1"/>正常</label>
<label><input type="radio" name="2_jcl_xz" value="2"/>不正常</label>
</td>
<td><input type="text" class="cs" name="2_jcl_cs"/></td>
<td><input type="text" class="bz" name="2_jcl_bz"/></td>
</tr>
<tr>
<td>二所站点C</td>
<td>
<label><input type="radio" name="2_cy_xz" value="1"/>正常</label>
<label><input type="radio" name="2_cy_xz" value="2"/>不正常</label>
</td>
<td><input type="text" class="cs" name="2_cy_cs"/></td>
<td><input type="text" class="bz" name="2_cy_bz"/></td>
</tr>
<tr>
<td>二所站点D</td>
<td>
<label><input type="radio" name="2_yjy_xz" value="1"/>正常</label>
<label><input type="radio" name="2_yjy_xz" value="2"/>不正常</label>
</td>
<td><input type="text" class="cs" name="2_yjy_cs"/></td>
<td><input type="text" class="bz" name="2_yjy_bz"/></td>
</tr>
</table>
</td>
</tr>
<tr>
</table>
</td>
</tr>

</table>
</form>
</div>

js对html的表单元素序列化封装并传递到后台

var d = new Date(),date = ''; 
date += d.getFullYear()+'';
date += d.getMonth() + 1+'';
date += d.getDate();

var str = 'NO.TYZXC-'+date+'-'+ids;

var form=$("#paramForm").serializeArray();
var data= arrayToJson(form);

param = {"xcbh":xcbh,"ids":ids,"str":str,"requestParam":data}
function arrayToJson(formArray){
var dataArray = {};
$.each(formArray,function(){
if(dataArray[this.name]){
if(!dataArray[this.name].push){
dataArray[this.name] = [dataArray[this.name]];
}
dataArray[this.name].push(this.value || '');
}else{
dataArray[this.name] = this.value || '';
}
});
return JSON.stringify(dataArray);
}

$.ajax({
url:root + "/Addxctyz",
data:param,
type:"post",
dataType:"json",
success:function(data){
alert("保存成功");
$("#reloadGrid",$("body",parent.$("#cell").context)).click();
},
error:function(){
alert("服务器正忙,请稍后重试");
}
})

后台

定义Util对前台的数据进行封装

public class Utils {

public static List<HashMap<String, Object>> getTyzDataTitle(){
List<HashMap<String, Object>> dataList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> tyzDataTitle = new HashMap<String, Object>();
tyzDataTitle.put("dwmc", "一所");
tyzDataTitle.put("dwbm", "1");
tyzDataTitle.put("dwbm1", "2");
ArrayList<Object[]> zhandian = new ArrayList<Object[]>();
zhandian.add(new Object[]{"yz","一所站点A"});
zhandian.add(new Object[]{"tz","一所站点B"});
zhandian.add(new Object[]{"lq","一所站点C"});
zhandian.add(new Object[]{"sc","一所站点D"});
zhandian.add(new Object[]{"mf","一所站点E"});
tyzDataTitle.put("zd", zhandian);

ArrayList<Object[]> zhandian1 = new ArrayList<Object[]>();
zhandian1.add(new Object[]{"tzz","二所站点A"});
zhandian1.add(new Object[]{"jcl","二所站点B"});
zhandian1.add(new Object[]{"cy","二所站点C"});
zhandian1.add(new Object[]{"yjy","二所站点D"});
tyzDataTitle.put("zd1", zhandian1);

dataList.add(tyzDataTitle);
return dataList;
}

}

后台接收前台序列化封装的数据,并进行相应的操作

@Controller
public class AddTyzjkjf {

@SuppressWarnings("unchecked")
@RequestMapping("/Addxctyz")
@ResponseBody
public Boolean Addxctyz(HttpServletRequest request, HttpServletResponse response,String requestParam){
String str = request.getParameter("str");
String xcbh = request.getParameter("xcbh");
String ids = request.getParameter("ids");

JSONObject jsonObject= JSON.parseObject(requestParam);

String xcsj =jsonObject.getString("xcsj");
String zbddy = jsonObject.getString("zbddy");



if(!(ids==null||"null".equals(ids))){

String uSel = "update SY_TYZJKXC set TYZJKXC_RY=?,TYZJKXC_XCSJ=? where TYZJKXC_ID =?";
Object[] params = {zbddy,xcsj,xcbh};
SqlUtil.getExecutor().execute(uSel.toString(), params);

String lsSj = "select distinct TYZJKXCZB_SJ from SY_TYZJKXCZB where TYZJKXCZB_ID =?";
IBean lsTime = SqlUtil.getExecutor().queryForBean(lsSj, xcbh);
String lsTime1 = String.valueOf(lsTime.get("TYZJKXCZB_SJ")) ;


String delSql1 = "delete from SY_TYZJKXCZB where TYZJKXCZB_ID=?";
Object paramd1 = xcbh;
SqlUtil.getExecutor().execute(delSql1.toString(), paramd1);

List<HashMap<String, Object>> tyzDataTitle = Utils.getTyzDataTitle();
String dwbm = null;
String dwbm1 = null;
ArrayList<Object[]> zd = null;
ArrayList<Object[]> zd1 = null;
for (HashMap<String, Object> hashMap : tyzDataTitle) {
dwbm = String.valueOf(hashMap.get("dwbm"));
dwbm1 = String.valueOf(hashMap.get("dwbm1"));
dwbm2 = String.valueOf(hashMap.get("dwbm2"));
dwbm3 = String.valueOf(hashMap.get("dwbm3"));
dwbm4 = String.valueOf(hashMap.get("dwbm4"));
dwbm5 = String.valueOf(hashMap.get("dwbm5"));
dwbm6 = String.valueOf(hashMap.get("dwbm6"));
zd = (ArrayList<Object[]>) hashMap.get("zd");
zd1 = (ArrayList<Object[]>) hashMap.get("zd1");
String xzkey = null;
String cskey = null;
String bzkey = null;
String zdmc = null;

for (Object[] objects : zd) {
xzkey = dwbm+"_"+objects[0]+"_xz";
cskey = dwbm+"_"+objects[0]+"_cs";
bzkey = dwbm+"_"+objects[0]+"_bz";
zdmc = String.valueOf(objects[1]);

String ysxz = jsonObject.getString(xzkey);
String yscs = jsonObject.getString(cskey);
String ysbz = jsonObject.getString(bzkey);

Object[] param1 = {xcbh,zdmc,ysxz,yscs,ysbz,ids,lsTime1};
String sql1 = "insert into SY_TYZJKXCZB(ID,TYZJKXCZB_ID,TYZJKXCZB_ZM,TYZJKXCZB_YXZK,TYZJKXCZB_CLCS,TYZJKXCZB_BZ,TYZJKXCZB_DW,P_ID,TYZJKXCZB_SJ)VALUES((select decode(max(ID), null, 0, max(ID)+1) from SY_TYZJKXCZB),?,?,?,?,?,'一所',?,?)";
SqlUtil.getExecutor().execute(sql1.toString(), param1);
}

for (Object[] objects : zd1) {
xzkey = dwbm1+"_"+objects[0]+"_xz";
cskey = dwbm1+"_"+objects[0]+"_cs";
bzkey = dwbm1+"_"+objects[0]+"_bz";
zdmc = String.valueOf(objects[1]);

String ysxz = jsonObject.getString(xzkey);
String yscs = jsonObject.getString(cskey);
String ysbz = jsonObject.getString(bzkey);

Object[] param1 = {xcbh,zdmc,ysxz,yscs,ysbz,ids,lsTime1};
String sql1 = "insert into SY_TYZJKXCZB(ID,TYZJKXCZB_ID,TYZJKXCZB_ZM,TYZJKXCZB_YXZK,TYZJKXCZB_CLCS,TYZJKXCZB_BZ,TYZJKXCZB_DW,P_ID,TYZJKXCZB_SJ)VALUES((select decode(max(ID), null, 0, max(ID)+1) from SY_TYZJKXCZB),?,?,?,?,?,'二所',?,?)";
SqlUtil.getExecutor().execute(sql1.toString(), param1);
}
}
}

 

 

 

标签:jquery,function,null,return,name,源码,var,序列化,String
From: https://blog.51cto.com/u_11837698/6081936

相关文章

  • 深入学习jquery源码之jQuery的核心参数
    深入学习jquery源码之jQuery的核心参数jQuery([selector,[context]])概述这个函数接收一个包含CSS选择器的字符串,然后用这个字符串去匹配一组元素。jQuery的核心功能都是......
  • 深入学习jquery源码之is()与not()
    深入学习jquery源码之is()与not()is(expr|obj|ele|fn)概述根据选择器、DOM元素或jQuery对象来检测匹配元素集合,如果其中至少有一个元素符合这个给定的表达式就返回true。......
  • 深入学习jquery源码之arguments和callee
    深入学习jquery源码之argumentsjs中的函数其实是对象,函数名是对Function对象的引用,arguments这个对象不能显式创建,arguments对象只有函数开始时才可用。每创建一个函数,该......
  • 深入学习jquery源码之filter()与find()
    深入学习jquery源码之filter()与find()filter(expr|obj|ele|fn)概述筛选出与指定表达式匹配的元素集合。这个方法用于缩小匹配的范围。用逗号分隔多个表达式参数expr Strin......
  • 深入学习jquery源码之prop()与removeProp()
    深入学习jquery源码之prop()与removeProp()prop(name|properties|key,value|fn)概述获取在匹配的元素集中的第一个元素的属性值。随着一些内置属性的DOM元素或window对象,如......
  • 深入学习jquery源码之addClass()和toggleClass()与hasClass()
    深入学习jquery源码之addClass()和toggleClass()与hasClass()addClass(class|fn)概述为每个匹配的元素添加指定的类名。参数class String一个或多个要添加到元素中的CSS类......
  • 深入学习jquery源码之siblings()和children()与contents()
    深入学习jquery源码之siblings()和children()与contents()siblings([expr])概述取得一个包含匹配的元素集合中每一个元素的所有唯一同辈元素的元素集合。可以用可选的表达式......
  • 深入学习jquery源码之jQuery中高质量的代码
    深入学习jquery源码之jQuery中高质量的代码1、this指向的问题 functionStudent(name,age,grade,school){Person.apply(this,arguments);}他就具备了Pe......
  • 深入学习jquery源码之next()和nextAll()与nextUntil()
    深入学习jquery源码之next()和nextAll()与nextUntil()next([expr])概述取得一个包含匹配的元素集合中每一个元素紧邻的后面同辈元素的元素集合。这个函数只返回后面那个紧邻......
  • 深入学习java源码之Math.sin()与 Math.sqrt()
    深入学习java源码之Math.sin()与Math.sqrt()native关键字凡是一种语言,都希望是纯。比如解决某一个方案都喜欢就单单这个语言来写即可。Java平台有个用户和本地C代码进行互......