2017-10-20 100 views
1

所以,我必須解析一個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": 

我想借此srcwidthheight並插入像圖片:

<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。

+0

它不重複。我需要不同的感謝 –

回答

0

如果您使用的是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); 
+0

如果我嘗試使用你的代碼,我得到了這個: 未捕獲的SyntaxError:意外的標記<在位置0的JSON中 –

+0

@StefanIordache有一個錯字:我寫了$ thumnails而不是$縮略圖。 立即試用 – Dacklf

+0

是的,我從一開始就看到它。 我仍然從控制檯收到此消息。 未捕獲的SyntaxError:意外的標記<位於JSON位置0 at JSON.parse() at Function.oe.parseJSON –

0

可以在普通的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; 
+0

此解決方案對我無效。謝謝 –

0

瞄準它在你的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更多信息

+0

我有js和php在同一個文件 –

+0

,你不能在兩個文件中分開?或者嘗試刪除ajax對象中的url屬性 – Berserk