繁体   English   中英

我正在从javascript传递表单数据中的JSON。 并在php中访问该JSON。 它将“”替换为“

[英]I'm passing a JSON in form data from javascript. And accessing that JSON in php. It replaces “” to &quot

我使用将其转换为JSON后发送数组

var json_arr = JSON.stringify(info);

JSON是

{"1":"111112221111","2":"1111122211","3":"11111222"}

我将此JSON作为文本框的值发送(使用post方法在表单字段中)。

我将其打印在php文件中

$this->log->write($data['infoArray']);

它打印为

{"1":"111112221111","2":"1111122211","3":"11111222"}

我试过了

json_decode($data['infoArray'],true);

但它什么也不打印(空白)

所以当我尝试遍历它时,

foreach ( $data['infoArray'] as $key => $value) {

                    $this->log->write("key :".$key);
                    $this->log->write("value :".$value);
}

它引发警告

PHP警告:为foreach()提供了无效的参数

所以我的问题是

  1. 为什么将“”替换为“”。
  2. 如何遍历JSON,以便可以访问其中的键和值。
  1. 我不知道您的log()方法到底能做什么,所以我无法真正告诉您原因。
  2. json_decode() html_entity_decode()之前使用json_decode() -设置$data['infoArray']

尝试这个:

$decoded = json_decode( html_entity_decode( $data['infoArray'] ) );
foreach ( $decoded as $key => $value) {
    $this->log->write("key :".$key);
    $this->log->write("value :".$value);
}

1.为什么“”被“”替换。

实际上是" 它是用于显示引号的html格式。 我认为JSON希望避免将引号与JSON数组中的其他键值混合,因此将其替换为"

2.如何遍历JSON,以便可以访问其中的键和值。

尝试json_decode()

因此,对于警告,请尝试首先解码html特殊字符,然后使用JSON解码,然后在foreach中使用它:

$json_decoded = htmlspecialchars_decode(json_decode($data['infoArray']))
foreach ( $json_decoded  as $key => $value) { ...

infoArray是一个json字符串,而不是一个php数组(您必须首先使用json_decode php函数将发布的json字符串转换为php数组)。

" 是由log函数添加的(我想它是用某些html打印的),因此默认情况下(由该函数)双引号转义为"

由于JSON是作为文本框的值发布的,因此转义可能在此处完成,并且" 在postinbg到php之前被替换。 使用html_entity_decode使用前json_decode 尽管首先将json数据作为文本字段的一部分传递似乎很尴尬

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM