BloggerAds

2011年6月6日 星期一

Codeigniter上實現Ajax (使用jQuery)

下面這個在Codeigniter上實現Ajax的方式,是透過jQuery的post方法來實現,首先寫好一個controller,controller的程式範例如下:
<?php
class testAjax extends CI_Controller {
function index() {
}
function testPost() {
echo "result=".$this->input->post('para');
}
 function testPara($strPara) {
echo "result=".$strPara;
}
}
?>
上面有兩個function,分別是以post (testPost)、傳入參數 (testPara)兩種方式來呈現,其實只要選擇一種來實作即可,可以自已選擇自已喜歡的方式。View的程式範例如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<title></title>
</head>
<body>
    <script language='javascript'>
    //<![CDATA[
    function testAjaxPost() {     
      var options = {'para' : '[在這輸入para的值]'};
   
    $.post('/index.php/testAjax/testPost', options, function(data) {
           alert(data);
    });
    }

    function testAjaxPara() {            
       $.post('/index.php/testAjax/testPara/[在這輸入要傳入$strPara的值]', null, function(data) {
         alert(data); 
     });
    } 
    //]]>
    </script>
 
<form id='frm1' method='post'>
<table border="0">
<tr>
<td>
<input type='button' id='btnTestPost' value='Post' onclick='testAjaxPost();' />
<input type='button' id='btnTestPara' value='Para' onclick='testAjaxPara();' />
</td>
</tr>
</table>
</form>    
</body>
</html>
這樣就可以執行了,jQuery的post說明如下:
$.post(URL [,POST_Para] [,Success] [,Fail]);

URL:Server端的URL。
POST_Para:要以Post方式傳入的陣列變數(不需使用時,可不傳入)。
Success:成功時要執行的程式碼(不需使用時,可不傳入)。
Fail:失敗時要執行的程式碼(不需使用時,可不傳入)。
其中傳入參數(testAjaxPara)方式,可以直接在網址輸入參數的值
而Post (testAjaxPost)方式則是透過javascript的陣列來傳入參數的值。

若要做比較進階的Ajax運用,可以在controller將值輸出成json或xml格式,就可以做到更多的功能

參考:http://stackoverflow.com/questions/308054/learning-how-to-use-ajax-with-codeigniter

2 則留言: