如何将form内的表单序列化为json字符串
2个回答
展开全部
在web开发过程中,经常遇到将form序列化不能格式的字符串提交到后台,下面就介绍怎样将form表单序列化为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;
};
/添加基本的资料
function addPersonInfo(){
//序列化form
var data = $('#personInfo').serializeObject();
$.ajax({
type:"post",
dataType: "json",
url:"http://192.168.0.167:8080/app/user/addPersonInfo.json?userId=3",
data:JSON.stringify(data),
contentType: "application/json;charset=utf-8",
success: function(msg) {
var notice = eval(msg);
if(notice.type=="success"){
alert(notice.msg);
window.location.href=notice.data.url;
}else if(notice.type=="validFail"){
$.each( notice.errors, function(index, dataValidMsg)
{
alert(dataValidMsg.msg );
});
}else if(notice.type="fail"){
alert(notice.msg);
}
},
error: function(msg) {
var notice = eval(msg);
alert(notice.msg);
}
});
}
//序列话
$.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;
};
/添加基本的资料
function addPersonInfo(){
//序列化form
var data = $('#personInfo').serializeObject();
$.ajax({
type:"post",
dataType: "json",
url:"http://192.168.0.167:8080/app/user/addPersonInfo.json?userId=3",
data:JSON.stringify(data),
contentType: "application/json;charset=utf-8",
success: function(msg) {
var notice = eval(msg);
if(notice.type=="success"){
alert(notice.msg);
window.location.href=notice.data.url;
}else if(notice.type=="validFail"){
$.each( notice.errors, function(index, dataValidMsg)
{
alert(dataValidMsg.msg );
});
}else if(notice.type="fail"){
alert(notice.msg);
}
},
error: function(msg) {
var notice = eval(msg);
alert(notice.msg);
}
});
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询