使用jQuery設(shè)計(jì)數(shù)據(jù)表格之實(shí)現(xiàn)Ajax功能
當(dāng)前在Web開(kāi)發(fā)中,jQuery和PHP無(wú)疑是絕佳的配合。其中PHP由于其簡(jiǎn)單易用,深得開(kāi)發(fā)者的喜愛(ài),而jQuery則由于在前端開(kāi)發(fā)中的靈活和簡(jiǎn)單,功能強(qiáng)大,可以做出很多很眩目的效果。在上篇文章中,主要講述了設(shè)計(jì)表格基類,本文將主要介紹測(cè)試和運(yùn)行部分,以及加入AJAX功能,整合jQuery。
測(cè)試運(yùn)行
現(xiàn)在,我們可以在CI中測(cè)試運(yùn)行下我們所寫的數(shù)據(jù)表格助手類是否有效果,在測(cè)試前,先在MYSQL中建立數(shù)據(jù)表如下:
- CREATE DATABASE `dg_test`;
- CREATE TABLE `users` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `username` varchar(80) NOT NULL,
- `password` varchar(32) NOT NULL,
- `email` varchar(255) NOT NULL,
- UNIQUE KEY `id` (`id`)
- ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
并插入一些初始數(shù)據(jù)
- INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES
- (1, 'david', '12345', 'david@domain.com'),
- (2, 'maria', '464y3y', 'maria@domain.com'), (3, 'alejandro', 'a42352fawet', 'alejandro@domain.com'),
- (4, 'emma', 'f22a3455b2', 'emma@domain.com'
接下來(lái),編寫控制層的測(cè)試文件,命名為test.php,保存在application/controller目錄下,代碼如下:
- class Test extends CI_Controller{
- function __construct(){
- parent::__construct();
- $this->load->helper(array('datagrid','url'));
- $this->Datagrid = new Datagrid('users','id');
- }
- function index(){
- $this->load->helper('form');
- $this->load->library('session');
- $this->Datagrid->hidePkCol(true);
- $this->Datagrid->setHeadings(array('email'=>'E-mail'));
- $this->Datagrid->ignoreFields(array('password'));
- if($error = $this->session->flashdata('form_error')){
- echo "$error";
- }
- echo form_open('test/proc');
- echo $this->Datagrid->generate();
- echo Datagrid::createButton('delete','Delete');
- echo form_close();
- }
- function proc($request_type = ''){
- $this->load->helper('url');
- if($action = Datagrid::getPostAction()){
- $error = "";
- switch($action){
- case 'delete' :
- if(!$this->Datagrid->deletePostSelection()){
- $error = 'Items could not be deleted';
- }
- break;
- }
- if($request_type!='ajax'){
- $this->load->library('session');
- $this->session->set_flashdata('form_error',$error);
- redirect('test/index');
- } else {
- echo json_encode(array('error' => $error));
- }
- } else {
- die("Bad Request");
- } }
- }
- ?>
下面簡(jiǎn)單分析下這個(gè)測(cè)試類文件。首先在其構(gòu)造函數(shù)中,加載了編寫的datagrid數(shù)據(jù)表格helper文件和CI中的url helper類,并且通過(guò)
- $this->Datagrid = new Datagrid('users','id');
初始化了數(shù)據(jù)助手類的構(gòu)造方法,指定了表名是users,數(shù)據(jù)列為id。接著,通過(guò)
- $this->Datagrid->setHeadings(array('email'=>'E-mail'));
設(shè)置了要顯示的表頭中,將email顯示為E-MAIL。并通過(guò)
- $this->Datagrid->ignoreFields(array('password'));
設(shè)置了,在數(shù)據(jù)表格列中不顯示password一列。再接下來(lái),則是調(diào)用generate()方法生成表格。而在proc()方法中,則負(fù)責(zé)處理用戶對(duì)選擇并刪除記錄的處理,而在if($request_type!='ajax'){ ……}的這段代碼中,則判斷是否屬于ajax調(diào)用,如果不屬于ajax調(diào)用,則正常返回出錯(cuò)提示信息,否則則使用json_encode方法返回錯(cuò)誤信息,這個(gè)技巧也是很常用的,之所以這樣做,其目的是為了能同時(shí)滿足ajax及非ajax的調(diào)用。
最后運(yùn)行的效果如下圖:

整合jQuery加入AJAX功能
現(xiàn)在,我們可以為其加入AJAX功能了,這就要整合jQuery。由于本文不是初學(xué)者的教程,因此不會(huì)講解jQuery方面的知識(shí),而是直接講解如何整合。首先新建一個(gè)文件夾,命名為js,然后里面放置jQuery的庫(kù)文件,并且新建立user.php文件,代碼如下:
- <html>
- <head>
- <title>Users Management</title>
- <script src="<?php echo base_url(); ?>js/jquery-1.6.3.min.js"></script>
- <script src="<?php echo base_url(); ?>js/datagrid.js"></script>
- </head>
- <body>
- <?php
- $this->Datagrid->hidePkCol(true);
- if($error = $this->session->flashdata('form_error')){
- echo "<font color=red>$error</font>";
- }
- echo form_open('test/proc',array('class'=>'dg_form'));
- echo $this->Datagrid->generate();
- echo Datagrid::createButton('delete','Delete');
- echo form_close();
- ?>
- </body>
- </html>
由于我們這里是采用ajax的方式去判斷用戶選擇表中的哪些記錄并且響應(yīng)刪除按鈕的事件,所以只保留上面的php代碼,而同時(shí),在js目錄下新建立一個(gè)js/datagrid.js文件,還要修改上文中的index 方法如下:
- function index(){
- $this->load->helper('form');
- $this->load->library('session');
- $this->load->view('users');
- }
也可以修改相關(guān)的CSS樣式,例如:
- .dg_form table{
- border:1px solid silver;
- }
- .dg_form th{
- background-color:gray;
- font-family:"Courier New", Courier, mono;
- font-size:12px;
- }
- .dg_form td{
- background-color:gainsboro;
- font-size:12px;
- }
- .dg_form input[type=submit]{
- margin-top:2px;
- }
在datagrid.js中,增加如下的函數(shù)方法:
- $(function() {
- $('.dg_form :submit').click(function(e){
- e.preventDefault();
- var $form = $(this).parents('form');
- var action_name = $(this).attr('class').replace("dg_action_","");
- var action_control = $('');
- $form.append(action_control);
- var post_data = $form.serialize();
- action_control.remove();
- var script = $form.attr('action')+'/ajax';
- $.post(script, post_data, function(resp){
- if(resp.error){
- alert(resp.error);
- } else {
- switch(action_name){
- case 'delete' :
- //將已刪除的數(shù)據(jù)在數(shù)據(jù)表格中移走
- $form.find('.dg_check_item:checked').parents('tr').remove();
- break;
- case 'anotherAction' :
- ..
- break;
- }
- }
- }, 'json')
- })
- })
在上面的代碼中,首先通過(guò) var $form = $(this).parents('form');獲得了表單的名,然后通過(guò)
- var action_name = $(this).attr('class').replace("dg_action_","")
獲得action的名稱,而
- var action_control = $('');
- $form.append(action_control);
則是動(dòng)態(tài)生成隱藏域action_control,通過(guò)$form.append(action_control)添加到表單中去。
接下來(lái),我們將客戶端的數(shù)據(jù)通過(guò) $.post(script, post_data, function(resp)發(fā)送到服務(wù)端,其中script變量定義了ajax發(fā)送的路徑,
Post_data則為通過(guò)$form.serialize()序列化后的表單數(shù)據(jù)。然后,在其回調(diào)函數(shù)的返回值中,判斷resp是否包含了錯(cuò)誤信息,如果包含了錯(cuò)誤信息則通過(guò)alert顯示,然后再在數(shù)據(jù)表格中,使用
- $form.find('.dg_check_item:checked').parents('tr').remove();
一句代碼,將服務(wù)端已刪除的數(shù)據(jù)行在數(shù)據(jù)表格中移走。
最后,我們?cè)偬砑尤缦麓a
- $('.dg_check_toggler').click(function(){
- var checkboxes = $(this).parents('table').find('.dg_check_item');
- if($(this).is(':checked')){
- checkboxes.attr('checked','true');
- } else {
- checkboxes.removeAttr('checked');
- }
- })
這段代碼的意思是,當(dāng)用戶選擇了表格中的“全選”按鈕時(shí),將會(huì)尋找表格中所有每一行記錄前的checkbox(存放到變量checkboxes中),然后如果用戶在全選的checkbox框中勾選了的話,則通過(guò)jQuery設(shè)置所有記錄前的checkbox的attr屬性為true,即實(shí)現(xiàn)了全選的功能,反之則為取消全選。
小結(jié)
本文使用了php中的著名開(kāi)發(fā)框架CI以及jQuery,指導(dǎo)讀者如何構(gòu)建了一個(gè)通用的數(shù)據(jù)表格幫助類,并且擁有ajax的功能(借助jQuery實(shí)現(xiàn))。讀者從中可以學(xué)到不少CI框架以及jQuery的技巧和知識(shí)。
原文:http://tech.it168.com/a2011/1027/1264/000001264981_all.shtml
【編輯推薦】