0

What is the quickest way using jQuery to build a JSON string with a constantly changing amount of fields?

I've searched high and low and have seen a few ways to do this, but none seem to be labeled as better or faster.

The code below looks to be the quickest to write, but does it have any drawbacks? It also looks like you can't append any additional data you might need that doesn't have an input field for it. Or can you?

$.ajax({
  type: 'post',
  url: url,
  data: inputs,
  success: function(result) {
     $('.change').html(result);
   }
});

Is using .each and creating the string yourself better in any way? Anyone who can shed some light on how to go about designing the best method?

Chris Bornhoft
  • 4,195
  • 4
  • 37
  • 55
  • Take a look at this question: http://stackoverflow.com/questions/1184624/serialize-form-to-json-with-jquery – Jose Vega Nov 21 '11 at 03:00

1 Answers1

0

See my answer to this very similar question.

If you're populating your data from the contents of form fields, there are several ways. You could:

  • apply some particular class to each element and select against it, appending the value of each matching element to your object literal

  • if you have the DOM ids of all relevant fields, loop through them

  • if all of the target elements are sibling children of a given element, select against that element's children

...are three possibilities that come to mind. Most of the time, though, you'll find it's less error-prone to pass an object literal and let jQuery worry about the shipping and handling than it is to build a string yourself.

Community
  • 1
  • 1
Christopher
  • 764
  • 4
  • 6