Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript String object is being split into an array on jQuery.post

I'm using jQuery to do ajax calls - many of which are working fine, but I've just run into an odd problem trying to send a string to the server. I've narrowed the code down to just this:

var x = new String('updateGroup');
var y = 'updateGroup';
$.post('page.aspx', {
    f: x,
    f2: y
}, function(data) {
});

When it hits the server however, the request variables are as follows:

Request["f"]          null          string
Request["f2"]         "updateGroup" string
Request.Form.AllKeys  {string[12]}  string[]
  [0]                 "f[0]"        string
  [1]                 "f[1]"        string
  [2]                 "f[2]"        string
  [3]                 "f[3]"        string
  [4]                 "f[4]"        string
  [5]                 "f[5]"        string
  [6]                 "f[6]"        string
  [7]                 "f[7]"        string
  [8]                 "f[8]"        string
  [9]                 "f[9]"        string
  [10]                "f[10]"       string
  [11]                "f2"          string

where Request["f[0]"] contains "u" etc.

Can someone explain why this happens?

like image 276
James Thorpe Avatar asked Dec 30 '11 12:12

James Thorpe


2 Answers

If you throw away all details, what's being executed in your case is:

  • jQuery.post
  • which calls jQuery.ajax internally to do the ajax
  • which calls jQuery.param internally to build the query string

The point is that new String is not a primitive string but a string object, and will pass the following check in jQuery.ajax (typeof new String("foo") === "object", not "string"):

// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
    s.data = jQuery.param( s.data, s.traditional );
}

jQuery.param is executing as follows:

for ( var prefix in a ) {
    buildParams( prefix, a[ prefix ], traditional, add );
}

This means it does a for in loop over the string, which indeed puts each character separately in the query string.

You can check this behaviour with this testcase:

var x = new String("abc");

for(var i in x) {
    console.log(i, x[i]);
}

// 0  "a"
// 1  "b"
// 2  "c"
like image 180
pimvdb Avatar answered Sep 18 '22 09:09

pimvdb


When you use new String you create a string object rather than a string itself, if you run this in your browser you will see they're an object and a string respectfully:

console.log(typeof new String("hello"));
console.log(typeof "hello");

More information here (including why you can an array of characters posted to the server): http://www.devguru.com/technologies/ecmascript/quickref/string.html

like image 23
oodavid Avatar answered Sep 19 '22 09:09

oodavid