我有一个 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 );
关于javascript - JSON 解码不适用于 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30093787/