将php json解析为javascript
因此,我必须将php json解析为javascript 代码如下所示:将php json解析为javascript,javascript,php,jquery,json,yii,Javascript,Php,Jquery,Json,Yii,因此,我必须将php json解析为javascript 代码如下所示: $thumbnails = []; foreach ($images as $key => $image) { $thumbnails[$image->time] = [ 'src' => MovieEntity::getImageWithPublicPath( $movie->id, $image->filename, 130, 0, false ),
$thumbnails = [];
foreach ($images as $key => $image)
{
$thumbnails[$image->time] = [
'src' => MovieEntity::getImageWithPublicPath(
$movie->id, $image->filename, 130, 0, false
),
'width' => '165px',
'height' => '95px'
];
}
return json_encode($thumbnails, JSON_UNESCAPED_SLASHES);
结果是:
{"5":{"src":"google.ro","width":"165px","height":"95px"},"7":
我想拍摄src
、width
和height
并将它们作为图片插入,如:
<a href="">
<img src="src of image" width="" height="">
</a>
乐:我的解决方案是:
<?= '<script>var json='.$thumbnails.'</script>' ?>
console.log(json);
log(json);
这将在控制台中返回json。如果您使用的是jQuery:
如果您使用的是纯javascript:
//jQuery snipet
var缩略图=$.parseJSON(“”);
log(thumbnails.src);
控制台。日志(缩略图。宽度);
控制台。日志(缩略图。高度);
如果您使用的是jQuery:
如果您使用的是纯javascript:
//jQuery snipet
var缩略图=$.parseJSON(“”);
log(thumbnails.src);
控制台。日志(缩略图。宽度);
控制台。日志(缩略图。高度);
您可以在纯JavaScript中执行此操作
将JSON回送到脚本标记中
<script type="application/json" id="json">
<?php echo $thumbnails; ?>
</script>
您可以用普通JavaScript实现这一点 将JSON回送到脚本标记中
<script type="application/json" id="json">
<?php echo $thumbnails; ?>
</script>
在javascript中,您必须通过执行get请求来请求php函数(假设您使用jQuery)。之后,在成功回调中,您将获得数据。因此,请尝试这样做:
$.ajax({
url : 'file.php', // your php file
type : 'GET', // type of the HTTP request
success : function(data){
var obj = jQuery.parseJSON(data);
console.log(obj);
}
});
您可以在javascript中获取更多信息,您必须通过执行get请求来请求php函数(假设您使用jQuery)。之后,在成功回调中,您将获得数据。因此,请尝试这样做:
$.ajax({
url : 'file.php', // your php file
type : 'GET', // type of the HTTP request
success : function(data){
var obj = jQuery.parseJSON(data);
console.log(obj);
}
});
如果我尝试使用您的代码,您可以查看更多信息,我得到了:Uncaught SyntaxError:Unexpected token<在JSON中的位置0@StefanIordache有一个打字错误:我写了$thumnails而不是$thumnails。现在试试看是的,我从一开始就看到了。我仍然从控制台收到这个消息。未捕获的SyntaxError:Function.oe的JSON.parse()位置0处的JSON中出现意外标记<。parseJSON@StefanIordache我能看看当你回显$thumbnails时,它会打印什么javascript代码吗?试试console.log(“”),让我看看JSON是否正确。如果我尝试使用您的代码,我会得到引号之间的字符串。我得到:Uncaught SyntaxError:Unexpected token<在JSON中的位置0@StefanIordache有一个打字错误:我写了$thumnails而不是$thumnails。现在试试看是的,我从一开始就看到了。我仍然从控制台收到这个消息。未捕获的SyntaxError:Function.oe的JSON.parse()位置0处的JSON中出现意外标记<。parseJSON@StefanIordache我能看看当你回显$thumbnails时,它会打印什么javascript代码吗?试试console.log(“”),让我看看JSON是否正确。我得到了引号之间的字符串。这个解决方案对我不适用。谢谢这个解决方案对我不起作用。这不是重复的。我需要不同的东西,不要重复。我需要一些不同的东西,谢谢我有在同一个文件中的js和php,你不能在两个文件中分开?或者尝试删除ajax对象中的url属性。我将js和php放在同一个文件中,并且不能在两个文件中分开?或者尝试删除ajax对象中的url属性
$.ajax({
url : 'file.php', // your php file
type : 'GET', // type of the HTTP request
success : function(data){
var obj = jQuery.parseJSON(data);
console.log(obj);
}
});