Please consider the following HTML:
<input type='text' id='name'/>
<option id='option'>
<select value='1'>hi</select>
<select value='2'>bye</select>
</option>
<input type='text' id='date'/>
This is a very simple form used to get search criteria from a user. I need to submit this search criteria to the server with an AJAX call. What is the best data type/structure to use to do this? And why?
I’m currently thinking a string vs. JSON object. So, I’ll either pass
"John|2|2010-10-10"
to the server or I’ll pass
{"name":"John","option":2,"date":"2010-10-10"}
Maybe there is some other creative way to deal with search criteria? This criteria is being shot to the server only one time, it doesn’t come back to JS.
If you wrap your HTML in a
<form>tag, you can easily use the$.serializeArray()function in jQuery.http://api.jquery.com/serializeArray/
$.serializeArray()creates a JavaScript object literal in the form of:[ {name: a, value:1}, {name: b, value: 2}, ...]This is done, I believe, because your form could have multiple fields with the same name. An associative array wouldn’t support this.
I’d recommend that you send your data to your server in a JSON format (using
serializeArrayor some other method) rather than a plain string. JSON is more standardized and can handle escaping characters. If you’re using pipe-delimited strings, then you have to take into account when a user wants to submit a pipe (|) to the server. Then you get into situations where you have crazy delimiters like||**between values. (I’ve seen this — it’s ugly!). Stick with JSON.If you’d prefer a more querystring-like format (e.g. a=1&b=2&c=3) that you can include in your request body, you can use
$.serialize().http://api.jquery.com/serialize/