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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33625248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:42:48  来源:igfitidea点击:

FormData sends boolean as string to server

javascriptangularjsapimultipartform-dataform-data

提问by user2099451

I have the following input which is a toggle returns true , false

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

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

and when I send it like this

当我像这样发送时

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

In the server I receive false and true as strings 'true', 'false'

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

How to solve this problem ?

如何解决这个问题呢 ?

回答by rckd

FormDatawill always be sent as strings. One way to solve the problem is to use JSON. Simply encode your values with JSON.stringifyon the clientside. On serverside you simply decode the values.

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

Clientside

客户端

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

Serverside (PHP, simplified)

服务器端(PHP,简化)

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

回答by kennyg

You could send each "checked item" as a string (which results in true) and not send the "unchecked items" (which could default to false on the server side.) For example:

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

Client Side (js/jquery)

客户端(js/jquery)

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') 

Server Side (php/laravel)

服务器端(php/laravel)

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

The ternary statements above will return false on null in php.

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

回答by аlex dyky?

use JSON.stringifyon client to send numbers and boolean values, then parse it on bakend

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

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

回答by paisley.london

I know it's incredibly late. But form data doesn't interpret type data e.g. booleans, integers etc..

我知道这太晚了。但是表单数据不会解释类型数据,例如布尔值、整数等。

The best way is to convert it to JSON, and cover the edge cases accordingly for booleans within.

最好的方法是将其转换为 JSON,并相应地涵盖其中布尔值的边缘情况。

e.g.

例如

const tryParseBoolean = value => {
  if (value === 'true') {
    return true
  }
  if (value === 'false') {
    return false
  }
  return value
}

const formEntriesToJson = entries => {
  const data = {}
  for (const [key, val] of entries) {
    data[key] = tryParseBoolean(val)
  }
  return data
}

回答by JLomaka

If you have a problem with boolean you need to send 0or 1.

如果您对 boolean 有问题,则需要发送0or 1

Example:

例子:

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

In many cases, the server will understand that this is a bool value: false = 0, true = 1

在许多情况下,服务器会明白,这是一个布尔值:false = 0true = 1

回答by Erichain

this is your ng-model:

这是你的ng-model

ng-model="event.is_active"

ng-model="event.is_active"

so, why not use ng-model="formData.event.is_active"instead ?

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

then, in your script file, you can directly send $scope.formDataas an object to the server.

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

回答by mic4ael

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

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