FormData将布尔值作为字符串发送到服务器 [英] FormData sends boolean as string to server

查看:932
本文介绍了FormData将布尔值作为字符串发送到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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}">

当我这样发送时

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

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

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

如何解决这个问题?

推荐答案

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

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:

客户端(js/jquery)

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

服务器端(php/laravel)

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;

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

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

这篇关于FormData将布尔值作为字符串发送到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆