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

查看:36
本文介绍了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);

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

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

如何解决这个问题?

推荐答案

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

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.

客户端

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,简化版)

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

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

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