【问题标题】:json_decoded hidden POST value doesn't return anything (or returns empty)json_decoded 隐藏的 POST 值不返回任何内容(或返回空)
【发布时间】:2019-01-16 11:43:37
【问题描述】:

解决方案:


正如 var_dump 所示,引号被替换为 ascii (?)

    'emails2bsent' => string '["email1@gmail.com","email2@gmail.com"]'

运行 preg_replace 并强制将它们改回常规引号解决了这个问题:

$_POST = preg_replace("/"/", "\"", $_POST);
$json = $_POST['emails2bsent'];
var_dump(json_decode($json));
var_dump(json_decode($json, true));

输出:

array (size=2)
    0 => string 'email1@gmail.com' (length=23)
    1 => string 'email2@gmail.com' (length=23)

array (size=2)
    0 => string 'email1@gmail.com' (length=23)
    1 => string 'email2@gmail.com' (length=23)

实际问题:

json_decode on POST 隐藏值。

我正在通过表单的隐藏字段发送一系列电子邮件:

<input name="emails2bsent" type="hidden" value='<?php echo json_encode($emails2bsent)?>' />

然后在尝试取回数组时:

$emails2bsent = json_decode($_POST['emails2bsent'], true);

$emails2bsent = json_decode($_POST['emails2bsent']);

它什么也不返回。 我做错了什么?


编辑:

目标页面上的 print_r 输出显示这些:

Array
(
    [reminder] => Some copy goes here,
    [button] => Send
    [go3] => three
    [reminder_ID] => 198
    [emails2bsent] => ["email1@gmail.com","email2@gmail.com"]
)

当我想访问 $_POST['emails2bsent']

echo($_POST['emails2bsent']);

我也可以。 它只是无法解码。我被困在这一点上,因为我想了解为什么这不起作用。我很久以前就已经对其进行了编程,但我无法在不知道它为什么不工作的情况下放手..

我可以知道为什么我得到了两张减票吗? 提问?


回复:阿迪森

发送前我的表单的输入字段:

<input name="emails2bsent" type="hidden" value="[&quot;email1@gmail.com&quot;,&quot;email2@gmail.com&quot;]">

我用来查看传递的数据的代码:

pre($_POST);
echo($_POST['emails2bsent']);
$out = json_decode($_POST['emails2bsent'], true);
echo '<br>out: ' . $out;

页面上的输出:

    Array
(
    [reminder] => The copy
    [button] => send
    [go3] => three
    [reminder_ID] => 198
    [emails2bsent] => ["email1@gmail.com","email2@gmail.com"]
)

["email1@gmail.com","email2@gmail.com"]
out: 

【问题讨论】:

  • var_dump($_POST); ,表单的html代码是什么?
  • $emails2bsent 变量是什么样的 (var_dump($emails2bsent))。
  • 如果 json_decode() 返回 null 表示解码数据失败。 php.net/manual/en/function.json-last-error-msg.php 可能会帮助您找出原因。正如其他人所说,您还应该检查原始输入值是否包含您所期望的。从提供的最小代码示例中,我们无法知道出了什么问题——我们需要更多信息。谢谢。
  • htmlspecialchars 没有做任何事情 :( 但是 json-last-error 显示错误号 4。我真的不明白这个 JSON 的东西......
  • JSON 只是一种以文本格式格式化和结构化数据的方式。这没什么特别复杂的。无论如何,错误代码 4 表示 JSON 中的语法错误(您可以在文档中查找此内容,或使用 json_last_error_msg() 获取错误的文本描述。现在,您说您的 $_POST["emails2bsent"] 值包含 ["email1@gmail.com","email2@gmail.com"] ,但正如this demo 所示,该数据不会导致 json_decode() 崩溃。您提供的数据不会重现问题

标签: php json hidden-field


【解决方案1】:

我怀疑您需要对 JSON 进行 HTML 编码:

<input name="emails2bsent"
       type="hidden"
       value="<?php echo htmlspecialchars(json_encode($emails2bsent)); ?>">

有效的 JSON 可能导致 HTML 无效,浏览器可能无法正确发布。

【讨论】:

  • 没有人知道,因为没有回答 cmets,但是,通常应该进行编码,尤其是双引号。 +1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-07
  • 2018-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-15
相关资源
最近更新 更多