BloggerAds

顯示具有 Codeigniter 標籤的文章。 顯示所有文章
顯示具有 Codeigniter 標籤的文章。 顯示所有文章

2011年6月20日 星期一

Codeigniter 使用POST方式實作jQuery UI中的AutoComplete(自動完成)

要在Codeigniter中利用jQuery來實作AutoComplete,目前比較受歡迎的,大概是這個 jQuery Plugins 及jQuery UI。jQuery Plugins透過POST來實作的方式Google一下就有很多,反而jQuery UI的討論比較少。

在jQuery UI的官方網站中的範例中,是使用 $.getJSON方式來傳輸入的值給Server端,程式如下:

$.getJSON( "search.php", {term: extractLast( request.term )}, response );
$.getJSON是使用GET方式,與Codeigniter預設是不開放GET有衝突到,所以要解決這個問題有兩種做法:
一、將Codeigniter中application/config/config.php中的 $config['enable_query_strings'] 設為 true
二、不要用 $.getJSON,改用$.ajax來抓server端的資料

下面就來說說第二種改用$.ajax來抓資料的方式。

Server端的程式如下:

$aryPara = array(
   $this->input->post('term') //抓term(使用者所輸入的值)
);

$sql = "SELECT col1 FROM table1 WHERE col1 LIKE CONCAT(?, '%');";
$result = $this->db->query($sql, $aryPara);        
if($result->num_rows() > 0){       
   $data= array(); //一定要轉成有label及value的array
    
   foreach($result->result() as $row){
      //設定資料, col1替換成你的欄位名稱
      $data[] = array('label'=> $row->col1, 'value'=> $row->col1);
   }
}
echo json_encode($data);
   
$result->free_result();
$this->db->close();  

Client端的程式如下:

$("#txtKeyword").bind("keydown", function( event ) {
    if ( event.keyCode === $.ui.keyCode.TAB &&
           $(this).data("autocomplete").menu.active ) {
       event.preventDefault();     
    }
})
.autocomplete({
    source: function(request, response) {
       $.ajax({url: "search.php",
           //注意:這裡是設定post的變數及值,Server端就是以這個變數名稱取值
           data: {term: extractLast( request.term )},  
           dataType: "json",
           type: "POST",
           success: function(data){
                   response(data);
           }
       });
    },     
    search: function() {
      var term = extractLast(this.value);
      if (term.length < 2 ) { //當字數小於兩個字時,不抓資料
          return false;
      }
    },
    focus: function() {return false;},
    select: function(event, ui) {
          var terms = split( this.value );
          terms.pop();
          terms.push( ui.item.value );
          terms.push( "" );
          this.value = terms.join( ", " );
          return false;
    }
});

function split( val ) {
    return val.split( /,\s*/ );
}
function extractLast(term) {
    return split( term ).pop();
}
這樣就大功告成了。

參考:
http://forum.jquery.com/topic/jquery-autocomplete-new-parameter-implemented-method-get-post
http://api.jquery.com/jQuery.getJSON/
http://jqueryui.com/demos/autocomplete/#multiple-remote

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