简体   繁体   English

将PHP对象数组转换为javascript数组

[英]Convert PHP objects array to javascript array

I retrieve image paths with the function get_all();. 我使用功能get_all();检索图像路径。 This get_all function retrieves images as an object. 此get_all函数将图像检索为对象。 This object has the attributes name, source_path and date. 该对象具有名称,source_path和date的属性。 I want my javascript to add images to a div. 我希望我的JavaScript将图像添加到div。 I have the following: 我有以下几点:

The instantiate.php includes files like Jquery and another JS file. Instantiate.php包括Jquery等文件和另一个JS文件。

<?php
    require_once("../../include/instantiate.php");    
    $photos = Photos::get_all();
    $JSPhotos;
    foreach($photos as $photo) { $JSPhotos + $photo->source_path; }
?>

<script type="text/javascript">
    $(document).ready(function() {
        var photos = <?php echo json_encode($JSPhotos); ?>;
        for(var i = 0; i <= 10; i++)
        {
            create_image("../"+photos[i]);
        }
    });

This does not work. 这是行不通的。 Anyone got a solution? 任何人都有解决方案吗? Solution in Jeroen's Post! Jeroen的帖子中的解决方案!

New Problem; 新问题;

In the create_image function I set the class and src of the image element. 在create_image函数中,设置图像元素的类和src。 When you click such an image I want an alert box to show up. 当您单击这样的图像时,我希望显示一个警告框。 I have checked if the class is set correctly, and I concluded that all images did have the classname "imgid". 我检查了该类的设置是否正确,并得出结论,所有图像的确具有类名“ imgid”。 So, any idea why this dont work? 所以,任何想法为什么这不起作用?

Script in the javascript part: javascript部分中的脚本:

$(".imgid").click(function() {
    alert("hey");
});

You are not assigning anything to your variable. 您没有为变量分配任何内容。

You probably want: 您可能想要:

$JSPhotos = array();
foreach($photos as $photo) {
  $JSPhotos[] = $photo->source_path;
}

Or something similar. 或类似的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM