好吧,您可以使用 jQuery,因为它易于使用且编写的代码更少。虽然我在这里给出了两种解决方案。
在 JavaScript 中:
$.fn.extractObject = function() {
var accum = {};
function add(accum, namev, value) {
if (namev.length == 1)
accum[namev[0]] = value;
else {
if (accum[namev[0]] == null)
accum[namev[0]] = {};
add(accum[namev[0]], namev.slice(1), value);
}
};
this.find('input, textarea, select').each(function() {
add(accum, $(this).attr('name').split('.'), $(this).val());
});
return accum;
}
// ...
var object = $('#testformId').extractObject();
console.log(object);
这里是演示:http: //jsfiddle.net/G2XVq/
在 jQuery 中:
$.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;
};
$(function() {
$('form').submit(function() {
$('#result').text(JSON.stringify($('form').serializeObject()));
return false;
});
});
(jQuery 部分取自这里)
这是演示:http: //jsfiddle.net/sxGtM/3/
用于通过 javascript 将数据发布到 php:
var str_json = JSON.stringify(myObject) //gives me the JSON string.
// AJAX XMLHttpRequest object in Javascript to send data to the server:
request= new XMLHttpRequestObject()
request.open("POST", "Phppage.php")
request.setRequestHeader("Content-type", "application/json", true)
request.send(str_json)