本文實例講述了ThinkPHP中使用ajax的方法,提交表單如下圖所示:
點擊提交,不需要刷新本頁,將內容提交到數據庫當中,并在本頁顯示提交的內容。如下圖所示:
一、jquery實現方法:
MessageAction.class.php頁面代碼如下:
模板index.html代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | < html > < head > < script type = "text/javascript" src = "__PUBLIC__/js/jquery-1.7.1.min.js" ></ script > < script type = "text/javascript" > $(function(){ $('input:button').click(function(){ var $title=$('input[name="title"]').val(); var $message=$('input[name="message"]').val(); $mess=$('#mess'); $.getJSON('__URL__/add',{title:$title,message:$message},function(json){ //alert(json);return false; if(json.status==1){ $mess.slideDown(3000,function(){ $mess.css('display','block'); }).html('標題為'+json.data.title+'信息為'+json.data.message); }else{ $mess.slideDown(3000,function(){ $mess.css('display','block'); }).html('信息添加失敗,請檢查'); } }); }) }) </ script > </ head > < body > < div style = "display:none; color:red;" id = "mess" ></ div > < form action = "" method = "get" > 標題:< input type = "text" name = "title" />< br /> 信息:< input type = "text" name = "message" />< br /> < input type = "button" value = "提交" /> </ form > </ body > </ html > |
二、ThinkPHP實現方法:
MessageAction.class.php頁面代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php class MessageAction extends Action{ function index(){ $this ->display(); } function addtwo(){ $m =M( 'message' ); if ( $vo = $m ->create()){ if ( $m ->add()){ $this ->ajaxReturn( $vo , '添加成功' ,1); } else { $this ->ajaxReturn(0, '添加失敗' ,0); } } else { $this ->error( $m ->getError()); } } } ?> |
模板index.html代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | < html > < head > < 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/ThinkAjax.js" ></ script > < script type = "text/javascript" > function add(){ //ThinkAjax.sendForm(表單ID,URL,回調函數,信息顯示的地方); ThinkAjax.sendForm('frm','__URL__/addtwo',wc); } function wc(data,status){ if(status!=1){ alert('發送失敗'); }else{ $('list').innerHTML+='標題'+data.title+',信息'+data.message; } } </ script > </ head > < body > < div id = "list" ></ div > < form action = "" 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 > |
感興趣的朋友可以測試運行一下本文所示實例,可以加深對Ajax應用的理解。