开发者

ajax image as response in php

I want to display an image as a response to an ajax call using php.. Does anybody have the complete code for this?? Please help me ou开发者_如何学运维t.. Thanks in advance..


Well I don't have the complete code to this, and if I did, I wouldn't give it to you.

You need to start off by creating an image using PHP's various image generation functions. To make it dynamic you could send it various parameters which are encoded in the url and can be fetched using the $_GET superglobal in php.

You would then set the src of an existing image placeholder element to the location of your dynamic image, then voila! Instant dynamic image.


You should use jQuery + JSON combination. You can convert php array into JSON format using json_encode.

index.php:

<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>

<a href='car.php' class='ajax'>Car Image</a>
<a href='bike.php' class='ajax'>Bike Image</a>

<div id="title">Title comes here</div>
<div id="image">Image comes here</div>

car.php:

<?php
$jsonArray['title'] = "Car";
$jsonArray['image'] = "<img src='images/car.jpeg'>";
echo json_encode($jsonArray);
?>

bike.php:

<?php
$jsonArray['title'] = "Bike";
$jsonArray['image'] = "<img src='images/bike.jpeg'>";
echo json_encode($jsonArray);
?>

ajax.js:

jQuery(document).ready(function(){

  jQuery('.ajax').click(function(event) {

      event.preventDefault();

      jQuery.getJSON(this.href, function(snippets) {
          for(var id in snippets) {
              jQuery('#' + id).html(snippets[id]);
          }
      });
  });

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜