FormData sends boolean as string to server

有些话、适合烂在心里 提交于 2020-07-14 06:17:51

问题


I have the following input which is a toggle returns 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'

How to solve this problem ?


回答1:


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

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)

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



回答2:


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:

Client Side (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)

$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.




回答3:


use JSON.stringify on client to send numbers and boolean values, then parse it on 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



回答4:


FormData.append(..) or FormData.set(..) converts values always to string (except if its Blob), see here:

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

formData.append('name', true);
formData.append('name', 74);
formData.append('name', 'John');

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

So you could use json encode/decode as suggested in https://stackoverflow.com/a/39094808/2311074

However, if its just that single value and you know it has to be a boolean but will be sent as a string, you may also just convert it to boolean on the server-side:

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



回答5:


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.

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
}



回答6:


If you have a problem with boolean you need to send 0 or 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




回答7:


this is your ng-model:

ng-model="event.is_active"

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

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




回答8:


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



来源:https://stackoverflow.com/questions/33625248/formdata-sends-boolean-as-string-to-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!