S
S
Sergey2011-02-08 17:28:27
JavaScript
Sergey, 2011-02-08 17:28:27

Sending boolean values ​​in jQuery.ajax() requests?

$.ajax({<br/>
 url : uri,<br/>
 type : 'post',<br/>
 data : {someBooleanVar1: false, subVar: {someBooleanVar2: true}}<br/>
});


The problem is that the server will receive the someBooleanVar1 and someBooleanVar2 variables as the strings "false" and "true", not "0" and "1".

The question is, is there some parameter or method in jQuery that automates the conversion of boolean values ​​to 0/1? Well, or if this cannot be implemented using jQuery, then maybe someone knows a simple way to bypass the object recursively by replacing boolean with number.

Thank you!

Answer the question

In order to leave comments, you need to log in

5 answer(s)
I
iStyx, 2011-02-08
@iStyx

Can be used like this:{ somevar1: boolVar?1:0 }

I
iStyx, 2011-02-08
@iStyx

I'm sorry, I missed the question about the replacement method. Try like this:

function bools2numbers(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;
}

The function modifies the passed array. If this does not fit, it is easy to replace it with copying.

T
theOnlyBoy, 2011-02-08
@theOnlyBoy

There is the following option, subject to some obvious limitations (and the presence of jQ 1.4+).

    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))
        }
    });

D
Dmitry, 2011-02-08
@Neir0

And why false and true do not roll? What is on the server side? Well, as a last resort, you can probably replace it with regexes, both when sending and when receiving.

I
Igor Alekseenko, 2011-03-12
@iamo0

Code saving option :)
{ myvar: bool + 0 }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question