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?
If you throw away all details, what's being executed in your case is:
jQuery.post
jQuery.ajax
internally to do the ajaxjQuery.param
internally to build the query stringThe 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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With