通过构造AJAX参数实现表单元素JSON相互转换
ajax提交服务器数据,整理一下转换方法。
HTML:
<formid="fm"name="fm"action=""> <inputname="UserName"type="text"value="UserName1"/> </form> <inputname="UserId"id="UserId"type="text"value="UserId1"/>
1.表单元素转QueryString
varq=$('#fm,#UserId').serialize();//q=UserName=UserName1&UserId=UserId1
2.字符串,JSON互相转换
varobj=jQuery.parseJSON('{"name":"John"}');
alert(obj.name==="John");
可以利用jquery-json插件实现转换,直接引用示例
varthing={plugin:'jquery-json',version:2.3};
varencoded=$.toJSON(thing);
//'{"plugin":"jquery-json","version":2.3}'
varname=$.evalJSON(encoded).plugin;
//"jquery-json"
varversion=$.evalJSON(encoded).version;
//2.3
3.表单,元素转Name,Value数组
vararr=$("#fm,#UserId").serializeArray();
/*[
{name:'UserName',value:'"UserName"1'},
{name:'UserId',value:'UserId'}
]*/
4.表单元素转JSON
$.fn.serializeObject=function()
{
varo={};
vara=this.serializeArray();
$.each(a,function(){
if(o[this.name]!==undefined){
if(!o[this.name].push){
o[this.name]=[o[this.name]];
}
o[this.name].push(this.value||'');
}else{
o[this.name]=this.value||'';
}
});
returno;
};
varobj=$('form').serializeObject();
/*obj:Object
UserId:"UserId1"
UserName:"UserName1"
__proto__:Object*/
5.JSON2FORM
$.getJSON('url_to_file',function(data){
for(variindata){
$('input[name="'+i+'"]').val(data[i]);
}
}
Google过程中发现一个更强大的插件http://code.google.com/p/jquery-load-json/
data={
"Name":"EmkayEntertainments",
"Address":"NobelHouse,RegentCentre",
"Contact":"Phone"
}
$('div#data').loadJSON(data);
<divid="data">
<h1id="Name">EmkayEntertainments</h1>
<labelfor="Address">Address:</label>
<spanid="Address">NobelHouse,RegentCentre</span>
<labelfor="Contact">Contactby:</label>
<spanid="Contact">Phone</span>
</div>热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短