我正在逐步学习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]);
}
});
});