JavaScript String object breaks into an array on jQuery.post

I use jQuery to make ajax calls - many of them work fine, but I just ran into an odd problem trying to send a string to the server. I narrowed the code down to this:

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

When it hits the server, the request variables look like this:

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 is happening?

+5
source share
4 answers

If you throw away all the details, then what happens in your case:

  • jQuery.post
  • which calls jQuery.ajaxinternally to execute ajax
  • which calls jQuery.paraminside to build a query string

, new String , 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 :

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

, for in , .

:

var x = new String("abc");

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

// 0  "a"
// 1  "b"
// 2  "c"
+3

, , , , , :

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

( , , ): http://www.devguru.com/technologies/ecmascript/quickref/string.html

+1

JavaScript String.
, jQuery , , , typeof string. , . ( String), - .

String, String.valueOf()

+1

​​ javascript, :

 var x = new String('updateGroup');

 var x = 'updateGroup';

, . ,

 var array = [];
+1

All Articles