ajax提交服务器数据, 整理一下转换方法。
html:
<form id="fm" name="fm" action="">
<input name="username" type="text" value="username1"/>
</form>
<input name="userid" id="userid" type="text" value="userid1"/>
1.表单元素转querystring
var q = $('#fm,#userid').serialize(); //q = username=username1&userid=userid1
2.字符串, json 互相转换
var obj = jquery.parsejson('{"name":"john"}');
alert( obj.name === "john" );
可以利用jquery-json插件实现转换,直接引用示例
var thing = {plugin: 'jquery-json', version: 2.3};
var encoded = $.tojson( thing );
// '{"plugin":"jquery-json","version":2.3}'
var name = $.evaljson( encoded ).plugin;
// "jquery-json"
var version = $.evaljson(encoded).version;
// 2.3
3.表单,元素转name,value数组
var arr = $("#fm,#userid").serializearray();
/*[
{name: 'username', value: '"username"1'},
{name: 'userid', value: 'userid'}
] */
4. 表单元素转json
$.fn.serializeobject = function()
{
var o = {};
var a = 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 || '';
}
});
return o;
};
var obj = $('form').serializeobject();
/*obj: object
userid: "userid1"
username: "username1"
__proto__: object*/
5. json2form
$.getjson('url_to_file', function(data) {
for (var i in data) {
$('input[name="'+i+'"]').val(data[i]);
}
}
google过程中发现一个更强大的插件 http://code.google.com/p/jquery-load-json/
data = {
"name":"emkay entertainments",
"address":"nobel house, regent centre",
"contact":"phone"
}
$('div#data').loadjson(data);
<div id="data">
<h1 id="name">emkay entertainments</h1>
<label for="address">address:</label>
<span id="address">nobel house, regent centre</span>
<label for="contact">contact by:</label>
<span id="contact">phone</span>
</div>