BloggerAds

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

沒有留言:

張貼留言