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

编程入门 行业动态 更新时间:2024-10-15 06:20:42
本文介绍了FormData 将布尔值作为字符串发送到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有以下输入,这是一个切换返回 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-18 15:25:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/942187.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发送到   字符串   服务器   布尔值   FormData

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!