Sending of Boolean values in queries jQuery.ajax()

0 like 0 dislike
10 views
$.ajax({
url : uri,
type : 'post',
data : {someBooleanVar1: false, subVar: {someBooleanVar2: true}}
});


The problem is that the server will get someBooleanVar1 and someBooleanVar2 variables as strings "false" and "true" instead of "0" and "1".

The question is whether there is in jQuery a parameter or method for automated conversion of Boolean values to 0/1? Or if you means jQuery is not realize, that maybe somebody knows a simple way to bypass the object recursively replacing the boolean to number.

Thank you!
by | 10 views

5 Answers

0 like 0 dislike
You can use this: { somevar1: boolVar?1:0 }
by
0 like 0 dislike
Sorry, missed the question about the method of replacement. Try this:
\r
\r
bools2numbers function(arr) { for(var i in arr) { var o = arr[i]; if(typeof o == 'object') bools2numbers(arr[i]); else if(typeof o == 'boolean') arr[i] = o?1:0; } return arr; }

\r
The function modifies the passed array. If it's not easily replaced by copying.
by
0 like 0 dislike
There is another option with some obvious restrictions (and the presence of jQ 1.4+).
\r
\r
function bool2Int(obj) { $.each(obj, function(i) { if (typeof obj[i] == 'object') { bool2Int(this); } else if (typeof obj[i] == 'boolean') { obj[i] = +obj[i]; } }); return obj; } $.ajaxSetup({ processData: false, beforeSend: function(xhr, settings) { settings.data = $.param(bool2Int(settings.data)) } }); 
by
0 like 0 dislike
Why are false and true does not roll? On the server side that costs? Well at the very least, probably reexami to replace both when sending and when receiving.
by
0 like 0 dislike
The option of saving the code :)
{ myvar: bool + 0 }
by

Related questions

0 like 0 dislike
4 answers
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
asked May 20, 2019 by Aleksander911
110,608 questions
257,186 answers
0 comments
32,865 users