关于javascript:FormData将布尔值作为字符串发送到服务器

FormData sends boolean as string to server

我有以下输入,这是一个切换,返回true,false

1
<input id="{{event.id}}" ng-model="event.is_active" type="checkbox" value="true" class="block__input" ng-class="{'input__toggle--active' :  event.is_active}">

当我这样发送时

1
2
3
 var formData = new FormData();
            console.log(scope.event.is_active);
            formData.append('is_active', scope.event.is_active);

在服务器中,我以字符串'true','false'接收到false和true

如何解决此问题?


FormData将始终作为字符串发送。解决此问题的一种方法是使用JSON。只需在客户端使用JSON.stringify对值进行编码。在服务器端,您只需解码值即可。

客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var fd = new FormData;
var data = {
    name: 'john doe',
    active: true,
    count: 42
};
var prop;
for(prop in data){
    fd.append(prop, JSON.stringify(data[prop]));
}

// if you want to upload files, too
fd.append('file', file);

$http({
    method: 'post',
    url: '/api/upload',
    data: fd,
    transformRequest: angular.identity,
    headers:{ 'Content-Type': undefined }
});

服务器端(PHP,简化版)

1
2
3
4
5
$data = [];
foreach($_POST as $prop => $value){
    $data[$prop] = json_decode($value);
}
// $data contains the correct values now ..

您可以将每个"选中的项目"作为字符串发送(结果为true),而不发送"未选中的项目"(在服务器端可能默认为false)。例如:

客户端(js / jquery)

1
2
3
4
5
6
7
8
var fd = new FormData();
var foo = $('[name="foo"]').prop('checked');
var bar = $('[name="bar"]').prop('checked');
var is_active = $('[name="is_active"]').prop('checked');

if (foo) fd.append('foo',foo);
if (bar) fd.append('bar', bar);
if (is_active) fd.append('is_active', is_active')

服务器端(php / laravel)

1
2
3
4
$foobar = new FooBar();
$foobar->foo = $request->foo ? true : false;
$foobar->bar = $request->bar ? true : false;
$foobar->is_active = $request->is_active ? true : false;

以上三元语句将在php中的null上返回false。


如果布尔值有问题,则需要发送01

示例:

1
2
3
let data = new FormData()
data.append('type', '0')
data.append('typeSend', '1')

在许多情况下,服务器将了解这是一个布尔值:false = 0true = 1


FormData.append(..)FormData.set(..)始终将值转换为字符串(Blob除外),请参见此处:

If the sent value is different than String or Blob it will be automatically converted to String:

1
2
3
4
5
formData.append('name', true);
formData.append('name', 74);
formData.append('name', 'John');

formData.getAll('name'); // ["true","74","John"]

因此您可以按照https://stackoverflow.com/a/39094808/2311074

中的建议使用json编码/解码

但是,如果它只是单个值,并且您知道它必须是布尔值,但将作为字符串发送,则也可以在服务器端将其转换为布尔值:

1
$is_active = ($this->request->is_active == 'true') ? true : false

在客户端上使用JSON.stringify发送数字和布尔值,然后在bakend

上对其进行解析

1
2
3
4
5
6
7
8
9
10
11
const form = new FormData;
const data = {
    name: 'john doe',
    active: true,
    count: 42
};

form .append('file', file); // send your file here
form .append('fileProps', JSON.stringify(data));

// then send form with POST from angular with using http

这是您的ng-model

ng-model="event.is_active"

那么,为什么不使用ng-model="formData.event.is_active"呢?

然后,您可以在脚本文件中直接将$scope.formData作为对象发送到服务器。


formData.append('is_active', scope.event.is_active === 'true');