按下按钮后更改图像链接

时间:2015-12-08 15:00:17

标签: javascript php jquery button

我正在博客中使用Bing图片搜索API。 我的要求回应:

stdClass Object

    (
        [d] => stdClass Object
            (
                [results] => Array
                    (
                        [0] => stdClass Object
                            (
                                [__metadata] => stdClass Object
                                    (
                                        [uri] => https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?Query='Kitchen'&Market='en-us'&$skip=0&$top=1
                                        [type] => ImageResult
                                    )

                                [ID] => a40b8c85-8a6b-45a8-bce2-c07b16a942e6
                                [Title] => Our Kitchen Remodel is Complete!!! @ A Well Dressed Home
                                [MediaUrl] => http://awelldressedhome.com/wp-content/uploads/2010/10/Kitchen-31.jpg
                                [SourceUrl] => http://awelldressedhome.com/496-our-kitchen-remodel-is-complete/
                                [DisplayUrl] => awelldressedhome.com/496-our-kitchen-remodel-is-complete
                                [Width] => 4000
                                [Height] => 3000
                                [FileSize] => 5062458
                                [ContentType] => image/jpeg

我在此响应中获得了50个结果(50个不同的图像和URL)。 我有一个PHP代码,在我的回复中给出了第一张图片的链接:

  <?php
            $context = stream_context_create($data);
            $response = file_get_contents($requestUri, 0, $context);
            $response=json_decode($response);
            $response = $response->d->results[0]->MediaUrl;
            echo "<pre>";
            print_r($response);
            echo "</pre>";
            echo '
                <td>
                 <img src="'.$response.'" height="100" weight="100">
                </td>
            ';
            echo("</ul>");
        ?>

我还做了一个简单的按钮,它给了我第一张图片,这是我在回复之前得到的:

<div class="form-group">
    <button onclick="myFunction()">Click me</button>
    <p id="demo"></p>
    <script>
        function myFunction()
        {
             document.getElementById("demo").innerHTML ="<?php echo "<img src=".$response." height='100' width='100'/>"?>"
        }
    </script>
</div>

所以问题是:每次点击我的按钮时,如何获得新图像? 对不起我的英文,谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

首先,您需要确保将您的网址写入javascript:

<?php
    $urlList = array();
    foreach($response->d->results as $r){
        $urlList[] = $r->MediaUrl;
    }
?>
<script>
    var urls = <?php echo json_encode($urlList); ?>;
</script>

然后你可以在你的函数中使用这些url:

<div class="form-group">
    <button onclick="myFunction()">Click me</button>
    <p id="demo"></p>
    <script>
        var currentIndex = 0;
        function myFunction(){
             document.getElementById("demo").innerHTML = "<img src='" + urls[currentIndex++ % urls.length]  + "' height='100' width='100'/>";
        }
    </script>
</div>