javascript - JSON 解码不适用于 PHP

标签 javascript php ajax json

我有一个 PHP 5.4.3 版本的 WAMP 服务器。我通过 php 文件将数据编码为 JSON,下面是代码 (submit.php)。

$username = 'User';
$comment = 'Test comment';
$date = date("Y-m-d G:i:s");  
$image = '/img/sephiroth.png';

  $return = array(
  'username'=> $username,
  'comment' => $comment,
  'date' => $date,
  'image' => $image  );
  echo json_encode($return); 

现在我有一个 javascript 文件(script.js)。

$.ajax({
            type: "POST",
            url: "submit.php",
            data: dataString,
            cache: false,
            success: function(result){
                    alert(result); //It is showing all the JSON data.
                    $value = result;
                    $data = json_decode($value,true);
                    alert($data);
                        }
           });

我想单独解码所有 JSON 数据。例如用户名、评论、日期、图像。所以,我可以在网页上显示它们,目前所有数据都汇集在一起​​。我多次尝试使用多个选项(php 数组或 result.username 或 result['username'] 但没有运气。

现在我遇到了以下错误。

ReferenceError: json_decode is not defined
    $data = json_decode($value,true);

最佳答案

不能在JS中使用json_decode json_decode是PHP函数

使用jQuery.parseJSON(json_data)来解析你的json数据;

jQuery.parseJSON( result );

改变

$value = result;
$data = json_decode($value,true);

致:

jQuery.parseJSON( result );

http://api.jquery.com/jQuery.parseJSON/

关于javascript - JSON 解码不适用于 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30093787/

相关文章:

javascript - JavaScript 代码出错?

javascript - 为什么我的 RestFul API 与express和nodejs每天都会崩溃?

javascript - 更改模块路径

javascript - Angular JS是否支持在同一页面上路由多个 View

php - 如何在不破坏标签的情况下剪辑 HTML 片段?

c# - ASP.NET MVC3 - 使用 Javascript 的错误

javascript - 我想执行从服务器获取的代码。我可以在我的控制台中获取代码。希望该代码在主浏览器页面上执行

php - 从 PHP Web 表单中的选项选择插入外键

java - 帮助搜索的开源工具

Javascript 不会加载到 ajax div 中