How to load more than two DIVs using an AJAX-JSON combination in zend?

I am learning AJAX in the zend framework step by step. I am using this question as a first step, and the accepted answer in this question works for me. Now I want to load more than one DIVs using JSON. Here is my plan.

IndexController.php:

class IndexController extends Zend_Controller_Action {

    public function indexAction() { }

    public function carAction() { }

    public function bikeAction() { }
}

index.phtml:

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

<a href='http://practice.dev/index/car' class='ajax'>Car Image</a>
<a href='http://practice.dev/index/bike' class='ajax'>Bike Image</a>

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

car.phtml

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

bike.phtml:

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

ajax.js:

jQuery(document).ready(function(){
    jQuery('.ajax').click(function(event){
       event.preventDefault();

       // I just need a js code here that: 
       // load "Car" in title div and car2.jped in image div when "Car Image" link clicked
       // load "Bike" in title div and bike2.jped in image div when "Bike Image" link clicked

      });
});

I think you have it. When any link with class = 'ajax' is clicked, it means its AJAX call. the array index (name, image) in phtml files (car.phtml, bike.phtml) shows in which DIV this content should be loaded.

My question is:

Now, how to implement ajax.js to do the job if it receives data in a json form?

thank

+2
2

JSON Zend Framework

echo Zend_Json::encode($jsonArray);

JSON , HTML. , JavaScript , , . JSON.

$jsonArray = array();
$jsonArray['title'] = "Hello";
$jsonArray['image'] = "<img src='images/bike.jpg' />";

JSON :

{
    "title": "Hello",
    "image": "<img src='images/bike.jpg' />"
}

, jQuery div - "image1" "image2".

jQuery('.ajax').click(function(event) {
    event.preventDefault();
    // load the href attribute of the link that was clicked
    jQuery.getJSON(this.href, function(snippets) {
        for(var id in snippets) {
            // updated to deal with any type of HTML
            jQuery('#' + id).html(snippets[id]);
        }
    });
});
+1

json, , {value1: "data", value2: "data2" } , ajax , ...

jQuery(document).ready(function(){
  jQuery('.ajax').click(function(event){
   event.preventDefault();
     $.ajax({
        url: '<Link to script returning json data>',
        data:json,   //says we are receiving json encoded data
        success: function(json) {
            $('#div1).html('<img src="'+json.value1+'"/>');
            $('#div2).html('<img src="'+json.value2+'"/>');
        }
     });

  });

});

0

All Articles