jQuery.ajax() and sending boolean request arguments
$.ajax({
url : uri,
type : 'post',
data : {someBooleanVar1: false, subVar: {someBooleanVar2: true}}
});
The problem is that on server someBooleanVar1 and someBooleanVar2 will be received as strings "false" and "true", but not as "0" and "1". Is there any way to automatically convert boolean arguments to "1" and "0"?
有一个固定版本的@jcubic答案:
function convertBoolToNum(obj) {
$.each(obj, function(i) {
if (typeof obj[i] == 'object') {
convertBoolToNum(this);
}
else if (typeof obj[i] == 'boolean') {
obj[i] = Number(obj[i]);
}
});
}
$.ajax = (function($ajax) {
return function(options) {
convertBoolToNum(options.data);
return $ajax(options);
};
})($.ajax);
试试这个,它应该自动将布尔值转换为数据选项中的数字。
$.ajax = (function($ajax) {
return function(options) {
if (options.data != undefined) {
for (var i in options.data) {
if (options.data.hasOwnProperty(i) &&
(typeof options.data[i] == "boolean")) {
options.data[i] = Number(options.data[i]);
}
}
}
return $ajax(options);
};
})($.ajax);
i know this post is a bit old but i still wanted to pass this information ^^ i pass vars to php and catch them with:
filter_var($var, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
like this i turn strings into booleans true=1
and false=
false as string is empty in php
maybe i read the question wrong. but this is what i understood :) with the code above you can easy build a function and add more filters to get everything work as you want :)
链接地址: http://www.djcxy.com/p/50708.html