Action
<?phpclass MessageAction extends Action{ public function index(){ $this->display(); } public function jquery(){ $this->display(); } public function add(){ $m=M('Message'); if ($vo=$m->create()){ if ($m->add()) {// $this->success('添加成功');//使用ajax $this->ajaxReturn($vo,'添加成功',1); }else{// $this->error('添加失敗');//使用ajax $this->ajaxReturn(0,'添加失敗',0); } }else{ $this->error($m->getError()); } } public function addjquery(){ //ajaxReturn() //返回json格式的資料 //參數一:資料;參數二:提示資訊;三:狀態 //echo $this->ajaxReturn(3,'提示資訊',2); $m=M('Message'); if ($m->add($_GET)){ $this->ajaxReturn($_GET,'添加資訊成功',1); }else{ $this->ajaxReturn(0,'添加資訊失敗',0); } }}?>
jquery.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><script type="text/javascript" src="__PUBLIC__/js/jquery-1.4.4.js"></script><script type="text/javascript">//標準ie可用,firefox不可用$(function(){$('input:button').click(function(){var $title=$('input[name="title"]').val();var $message=$('input[name="message"]').val();$msg=$('#msg');$.getJSON('__URL__/addjquery',{title:$title,message:$message},function(json){if(json.status==1){$msg.slideDown(2000,function(){$msg.css('display','block');}).html('標題為'+json.data.title+'資訊為'+json.data.message);}else{$msg.slideDown(2000,function(){$msg.css('display','block');}).html('資訊添加失敗,請檢查');}});})})</script><title></title></head><body><!-- 1.jquery執行個體,將jquery放入Public/js/之下 --><div style="display:none;color:red;" id="msg"></div><form action="__URL__/addjquery" method="get">標題:<input type="text" name="title"/><br/>資訊:<input type="text" name="message"/><br/><input type="button" value="提交"/><!-- 先設定為button不跳轉 --></form></body></html>
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><script type="text/javascript" src="__PUBLIC__/js/Base.js"></script><script type="text/javascript" src="__PUBLIC__/js/prototype.js"></script><script type="text/javascript" src="__PUBLIC__/js/mootools.js"></script><script type="text/javascript" src="__PUBLIC__/js/ajax/ThinkAjax.js"></script><script type="text/javascript">function add(){ThinkAjax.sendForm('frm','__URL__/add',callback,'result');}function callback(data,status){alert(status);if(status==1){$('msg').innerHTML+='標題'+data.title+',資訊'+data.message;}else{alert('參數錯誤');}}</script><title></title></head><body><!-- 1.ajax執行個體,將js檔案放入Public/js/之下 --><div style="color:red;" id="msg"></div><!-- 加入id,加入onclick事件 --><form action="__URL__/add" method="post" id="frm">標題:<input type="text" name="title"/><br/>資訊:<input type="text" name="message"/><br/><input type="button" value="提交" onclick="add()"/></form></body></html>