解析php json到javascript
所以,我必须解析一个php json到javascript中。解析php json到javascript
的代码看起来是这样的:
$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>
我需要做什么? PHP中的这个变量被称为$thumbnails
,它返回上面显示的JSON。
<?php echo $thumbnails ?>
LE:我的解决方案是:
<?= '<script>var json='.$thumbnails.'</script>' ?>
console.log(json);
这将返回在控制台中JSON。
如果您使用的是jQuery:$.parseJSON()。
如果你使用普通的JavaScript:JSON.parse()
// jQuery snipet
var thumbnails = $.parseJSON('<?php echo $thumbnails; ?>');
console.log(thumbnails.src);
console.log(thumbnails.width);
console.log(thumbnails.height);
如果我尝试使用你的代码,我得到了这个: 未捕获的SyntaxError:意外的标记
@StefanIordache有一个错字:我写了$ thumnails而不是$缩略图。 立即试用 – Dacklf
是的,我从一开始就看到它。 我仍然从控制台收到此消息。 未捕获的SyntaxError:意外的标记) at Function.oe.parseJSON –
可以在普通的JavaScript做到这一点。
回声的JSON插入脚本代码
<script type="application/json" id="json">
<?php echo $thumbnails; ?>
</script>
然后用JavaScript
var json = JSON.parse(document.getElementById('json').innerHTML);
var img = document.querySelector('img');
img.src = json.src;
img.width = json.width;
img.height = json.height;
此解决方案对我无效。谢谢 –
瞄准它在你的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);
}
});
你可以去here更多信息
我有js和php在同一个文件 –
,你不能在两个文件中分开?或者尝试删除ajax对象中的url属性 – Berserk
它不重复。我需要不同的感谢 –