在使用codeigniter前,我已经接触过一段时间的jquery了。Jquery高效的开发速度,良好的封装和简洁而灵活的语法都给我留下了很深刻的印象。 而它的ajax类让开发ajax成为了一种乐趣。你可以ajax类轻易的POST或者GET request。 它能帮助用户完成codeigniter不能完成的功能。 我才刚开始接触ci时间不长,ci轻巧而高效的框架同样给我留下了很深的印象。CI 的MVC 分离也做的非常的好,令人眼前一亮。但不可否认,ci也有它存在的问题。那就是对新技术的支持不够。类似json, ajax这些我们在网络开发中已经十分普及的技术,它都没有完成支持。 前些时间,由于自己想写一个php的项目,前段时间我调查了一下, 似乎大多数人都在使用xajax和其它封装好的php类。对此,我不是很喜欢,因为我一直认为框架会降低程序的执行效率。 所以我尝试着在ci框架中直接使用js框架jquery。 前天经过反复的试验,我找到了一个我自认为满意的方法, 并且发现在ci中实现ajax远比自己想像的简单。而且也没有像我自己想像的那样,破坏了MVC的完整性。
下面我把我的代码贴出来,和大家分享一下。
控制器:
复制内容到剪贴板
PHP 代码:
function getPhoto()
{
//query the picture from model
$query = $this->photomodel->getPic($_POST['picID']);
if($query->num_rows() > 0)
{
$row = $query->row();
$output = "<div class='winBar'><ul><li>_</li><li>x</li></ul></div><div class='winContent'><div id='photo_title'>" . $row->photoName . "</div><div id='photo_item'>" . $row->photoLink . "</div><div id='photo_comment'>" . $row->comment . "</div></div>";
}
else
$output = "no picture was found";
echo($output);
}
{
//query the picture from model
$query = $this->photomodel->getPic($_POST['picID']);
if($query->num_rows() > 0)
{
$row = $query->row();
$output = "<div class='winBar'><ul><li>_</li><li>x</li></ul></div><div class='winContent'><div id='photo_title'>" . $row->photoName . "</div><div id='photo_item'>" . $row->photoLink . "</div><div id='photo_comment'>" . $row->comment . "</div></div>";
}
else
$output = "no picture was found";
echo($output);
}
视图:
复制内容到剪贴板
JS 代码:
$(".photoblock").click(function(){
$("#photoboard").fadeOut("slow");
$(this).css("background-color","#7c2916");
$("#loading_message").show();
//post the pictureID to controller and return the picture and embed it to the photoboard.
$.ajax({
type:"post",
data: "picID=" + $(this).attr("id"),
url:"<?=base_url()?>photogallery/getPhoto",
success: function(result)
{
$("#photoboard").fadeTo("slow", 0.85).fadeIn("normal").html(result);
$("#photoboard").fadeOut("slow");
$(this).css("background-color","#7c2916");
$("#loading_message").show();
//post the pictureID to controller and return the picture and embed it to the photoboard.
$.ajax({
type:"post",
data: "picID=" + $(this).attr("id"),
url:"<?=base_url()?>photogallery/getPhoto",
success: function(result)
{
$("#photoboard").fadeTo("slow", 0.85).fadeIn("normal").html(result);
$("#loading_message").hide();
},
error: function()
{
$("#loading_message").hide();
alert("ajax error");
}
});
});
这是我写的 photo gallery 的部分代码。目的是在 php 页面中通过点击网页中图片的缩略图,来打开对应的图片进行浏览。
Code 很简单,我也不多解释了。大家需要注意的只是在用 jq post 或者 get 的时候, url 路径一定要用 base_url() 或者 site_url()。
在今后的日子里,如果我对 ci+jq 这一组合有了什么新的体会,我也会在这里和大家分享的。