2

Last night I was sending some data to my server via AJAX (specifically, $.post), when I ran into the issue that JavaScript Arrays needed to be "stringified" and applied as a field to an object before being sent. That is:

$.post("/myUrl/", {"myKey": json.stringify(myArray)}, ... );

If I didn't perform the stringify, the format of the POST would get screwed up by the time it reached Django.

Why do arrays need to be stringified for requests when objects can just be sent as is? Or, does this vary wildly on the back-end being used?

Casey Falk
  • 2,617
  • 1
  • 18
  • 29
  • 1
    The object doesn't get sent "as is". jQuery does some stuff to it to convert it to URL key/values: `http://this.url?myKey=stringifiedArray`. Objects are used because they're an easy data structure to manipulate. – Andy Aug 01 '14 at 12:33
  • Ah, interesting. So jQuery just doesn't do the same "stuff" to arrays -- or rather it treats them differently? – Casey Falk Aug 01 '14 at 12:35
  • Ahhh..... That would explain why the `request.POST` was broken into `list[index]` bits; it is trying to create unique key/value pairs from the array! Is that right? – Casey Falk Aug 01 '14 at 12:37
  • jQuery's post method accepts a data object (or string - see below) of key/value pairs. – Andy Aug 01 '14 at 12:40

1 Answers1

1

The object doesn't get sent "as is". jQuery recodes the object to URL key/values pairs, for example:

http://this.url?myKey=stringifiedArray.

The documentation has more information on this.

data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.

Objects are used because they're an easy data structure for developers to manipulate.

Andy
  • 61,948
  • 13
  • 68
  • 95
  • Hmmm... And an `Array` is an `Object`, but *not* a `PlainObject` is that the case? (http://stackoverflow.com/questions/5048371/are-javascript-arrays-primitives-strings-objects) – Casey Falk Aug 01 '14 at 12:39
  • The difference is an array is a list-like object that has numerical indexes and is sortable, and an object has key/value pairs wherein the keys must be unique and cannot be sorted. – Andy Aug 01 '14 at 12:42
  • BTW, the [MDN library](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference) is a great resource if you've never leafed through it. – Andy Aug 01 '14 at 12:45
  • Yeah, I've seen the MDN library -- thanks. :) I was actually just skimming through it (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). It looks like the big difference is the *plain* object (`{}`) vs the more general object class that contains arrays -- and it seems jQuery only handles the prior case by default. Interesting! Thanks, @Andy! – Casey Falk Aug 01 '14 at 12:54