Я всегда думал, что это было лениво для не использования их. Мне преподавали, что это должно всегда делаться. Но тогда, я не слушал обсуждение Joel. У него, возможно, было серьезное основание, я не знаю.
jQuery actually has something built-in for building the array: map()
var items = $('.nameList').find('li').map(function() {
var item = { };
item.id = this.value;
item.title = $(this).text();
return item;
});
That will build an array of objects matching the JSON structure you're after. Then, to JSON serialize that, use JSON.stringify which is built into newer browsers and available for older ones by including json2.js:
// Produces [{'id':1,'title':'bob'},{etc},{etc}]
var json = JSON.stringify(items);
Also keep in mind that $.post() automatically serializes an object data parameter, as key1=value1&key2=value2&etc. Unless you strictly need JSON on the server-side, the JSON serialization step may not be necessary.
var items = [];
$('ul.nameList').children().each(function() {
var $this = $(this);
var item = { id: $this.attr('value'), title: $this.html() };
items.push(item);
});