0

such that an object literal contains the parameters you want to send and the result is a string you can send as data.

Here is my first try:

function makeData(obj) {
    var data_send = '';
    _.each(obj, function (val, key) {
        data_send += encodeURIComponent(key) + '=' + encodeURIComponent(val) + '&';
    });
    data_send.slice(1,-1);
    return data_send;
}

Is this the correct form for ajax post data?

employee-0
  • 1,023
  • 1
  • 9
  • 19
  • What if val is an array? – Adam Jenkins Sep 12 '13 at 01:22
  • obj is assumed to be well formed - just key value pairs. – employee-0 Sep 12 '13 at 01:23
  • An array is a valid "value" in an object - and it can be passed as a valid query string parameters using [] like items[]=firstitem&items[]=seconditem – Adam Jenkins Sep 12 '13 at 01:24
  • Question has already been answered (quite well, too) http://stackoverflow.com/questions/1714786/querystring-encoding-of-a-javascript-object – Adam Jenkins Sep 12 '13 at 01:26
  • ...well I don't need to support that just yet, I want to make sure the simple case works first, particularly my use of `encodeURIComponent` – employee-0 Sep 12 '13 at 01:26
  • wow...that's not too efficient...pushing to an array just so you can create a string later ... my way is a bit more efficient. – employee-0 Sep 12 '13 at 01:28
  • Creating one tiny JS array that exists in memory for the duration of a function execution is a non-issue. Don't fool yourself into thinking that that somehow matters. – Adam Jenkins Sep 12 '13 at 10:02

0 Answers0