如何在zend中使用AJAX-JSON组合加载多个DIV?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了如何在zend中使用AJAX-JSON组合加载多个DIV?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在逐步学习zend框架中的 AJAX.我使用 this question作为第一步,这个问题的接受答案对我有用.现在我想使用JSON加载多个DIV.这是我的计划.

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

      });
});

我想你有这个.当点击任何带有class =’ajax’的链接时,它意味着它的AJAX调用. phtml文件(car.phtml,bike.phtml)中的数组索引(标题,图像)显示应该加载DIV这个内容.

我的问题:

现在,如果获取json表单中的数据,如何实现ajax.js来完成这项工作?

谢谢

Encode 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代码需要遍历每个键,并使用匹配键 – “image1”或“image2”将新图像注入div.

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]);
        }
    });
});

脚本宝典总结

以上是脚本宝典为你收集整理的如何在zend中使用AJAX-JSON组合加载多个DIV?全部内容,希望文章能够帮你解决如何在zend中使用AJAX-JSON组合加载多个DIV?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。