【问题标题】:encode json from javascript and decode using php从 javascript 编码 json 并使用 php 解码
【发布时间】:2012-12-23 08:16:58
【问题描述】:

我必须使用 javascript 将一组电子邮件地址编码为 json 字符串并使用 ajax 发送到 abc.php。在 abc.php 中,我必须对其进行解码并将电子邮件发送到该数组中的所有地址。

目前我正在使用

将数组编码为 json
var json_string = JSON.stringify(myarray);

在 abc.php 中,我正在使用

对其进行解码
$emails = json_decode($_POST['json_string']);
// json_string was passed as POST variable using ajax

但打印时它会给出 NULL..

如何解码并访问 php 文件中的单个电子邮件

【问题讨论】:

  • var_dump($_POST['json_string'])var_dump($_POST) 给你什么?
  • print_r 给出 [\"abc@gmail.com\",\"def@ptas.com.np\"] 和 var_dump (json_decode($_POST['json_string'])) 给出 null
  • 看起来像magic quotes?
  • 查看实际的 ajax 调用可能会有所帮助。它可能是一个数据类型的东西。
  • 是的,可能是魔术引号。尝试在解码前取消转义字符串。

标签: php javascript json


【解决方案1】:

如果您可以访问您的网络服务器的 php.ini,最好的办法是完全禁用 magic_quotes,因为它们已被弃用

; Magic quotes
;

; Magic quotes for incoming GET/POST/Cookie data.
magic_quotes_gpc = Off

; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc.
magic_quotes_runtime = Off

; Use Sybase-style magic quotes (escape ' with '' instead of \').
magic_quotes_sybase = Off

如果您没有服务器访问权限,请使用带有以下选项的 .htaccess 文件

php_flag magic_quotes_gpc Off

如果你不想使用它,最后剩下的就是使用 unescape 函数,例如

function ref_stripslashes(&$value,$key) {
    $value = stripslashes($value);
}

if((function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc()) || (ini_get('magic_quotes_sybase') && (strtolower(ini_get('magic_quotes_sybase'))!="off")) ) {
    array_walk_recursive($_GET,'ref_stripslashes');
    array_walk_recursive($_POST,'ref_stripslashes');
    array_walk_recursive($_COOKIE,'ref_stripslashes');
}

这取自the php manual, Lucifer's comment

json_decode($_POST['json_string']) 然后应该可以工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2016-05-01
    • 1970-01-01
    相关资源
    最近更新 更多