简体   繁体   English

如何将图像的PHP数组发送到Javascript数组并显示它们

[英]How to send PHP array of images to Javascript array and display them

Noobie here, Apologies if this question is silly, Noobie在这里,很抱歉这个问题很愚蠢,

I have developed a image match game with set of default images, now i want to access random images from directory for the game.The game logic is done in Javascript. 我已经开发了具有默认图像集的图像匹配游戏,现在我想从该游戏的目录中访问随机图像。游戏逻辑是用Javascript完成的。 I used php to get random 8 images from the directory and the code is as follows. 我使用php从目录中随机获取8张图像,代码如下。

random.php: random.php:

function getRandomImage() {
    $dire="Annotated Dataset/";
    $images = glob($dire. '*.{jpg,jpeg}', GLOB_BRACE);
    shuffle($images);
    $imgarray= array_slice($images,1,8);
    echo json_encode($imgarray);
}
die(json_encode(getRandomImage()));

The above displays file names of 8 images, but I want to display these 8 images in the following Javascript file inside if condition 上面显示了8张图片的文件名,但是如果条件允许,我想在下面的Javascript文件中显示这8张图片

game.js: game.js:

function getgImage(number) {
    var ranarray= "<?php echo json_encode($imgarray)?>";
    if(number=='1'){
        return '<img src="'+ranarray[1]+'">';
    }else if(number == '2'){
        return '<img src="'+ranarray[2]+'">';
    }else if(number == '3'){
        return '<img src="'+ranarray[3]+'">';
    }else if(number == '4'){
        return '<img src="'+ranarray[4]+'">';
    }else if(number == '5'){
        return '<img src="'+ranarray[5]+'">';
    }else if(number == '6'){
        return '<img src="'+ranarray[6]+'">';
    }else if(number == '7'){
        return '<img src="'+ranarray[7]+'">';
    }else if(number == '8'){
        return '<img src="'+ranarray[8]+'">';
    }else{
        return '<img src="resources/logo.png">';
    }
}

the above code i tried to get the images from the array in the php file ( random.php) but I am not able to display the images. 上面的代码我试图从php文件(random.php)中的数组中获取图像,但我无法显示图像。 Can someone provide a solution on how to proceed. 有人可以提供有关如何进行的解决方案。 I want the image array[1 to 8] from php to be set inside the If condition such that each image from the array is inside seperate if conditions. 我希望将来自php的图像array [1至8]设置为If条件,以使来自数组的每个图像都位于单独的if条件中。 Kindly help me with this problem. 请帮助我解决这个问题。

EDIT: Look at DubZ comment herunder for a good clue. 编辑:看看DubZ注释下的一条很好的线索。 :-) :-)

By the looks of it, you return only the imagename: 从外观上看,您仅返回图像名称:

<img src="'+ranarray[2]+'">

That will result in HTML: 这将导致HTML:

<img src="someimage.jpg">

Check your HTML to see what there is listed for the images. 检查您的HTML,以查看其中列出了图像。

Solution: 解:

Give the FULL URL. 输入完整网址。 eg: 例如:

<img src="http://www.yourgame.com/images/someimage.jpg">

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

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