1. 程式人生 > >jquery接收PHP傳送過來的JSON格式資料以及處理。

jquery接收PHP傳送過來的JSON格式資料以及處理。

本例使用的是YII框架。

PHP端

public function actionForlistbox(){
                $model=  SpecInfo::model()->findAllByAttributes(array('spec_id'=>2));
                $arr=array();
                foreach($model as $item){
                    $arr[]=$item->attributes['group'];
                }
            $js= json_encode($arr);
            echo $js;
        }

前端:

        <script type="text/javascript">
            $(document).ready(function(){
                var i=0;
                var j=1;
                $.ajax({
                    type:'post',
                    dataType:'json',
                    url:'./index.php?r=admin/TblGoods/forlistbox',
                    success:function(msg){
                        var arr=[];
                        $.each(msg,function(index,val){
                            arr[index]=val;
                        });
                        while(i<arr.length){
                            if((arr[j]-arr[i])>0){
                                $("#br"+j).after("<br/>");
                            }
                            i++;
                            j++;
                        }
                        $("#br"+i).after("<br/>");//最後那個複選框後面加一個BR,使用者分隔後面的全選框。
                    }
                });
            });
        </script>

完整程式碼:

tblGoodsController.php

<?php

class TblGoodsController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
        //每個控制器可以在這裡單獲設定佈局檔案By Ping 2014-2-20
	public $layout='//layouts/houtai';
        
        public $group=array();

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','forlistbox'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin','@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new TblGoods;

                
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
                //使用下拉選單,實現新增產品或修改產品時,可以從下拉列表選擇產品類別:以下為第1步
                //在Goods控制器下例項化category物件,並執行SQL語句,取得所有資料。
                $category =  TblCategory::model()->findAll();
                
                //如果有URL傳遞過的來分類ID,則表示這頁面是通過分型別表跳轉過來的。
                if(isset($_GET['cat_id'])){
                    //接收分類ID
                    $cat_id=$_GET['cat_id'];
                    //設定模型的預設分類
                    $model->cat_id=$cat_id;
                }

		if(isset($_POST['TblGoods']))
		{
			$model->attributes=$_POST['TblGoods'];
                        //yii checkBoxList 的高階使用
                        //將checkBoxList提交的資料,轉換成字串後再儲存到資料庫中。
                        //獲取顏色陣列後將陣列轉換成字串,用豆號分隔。並儲存到資料庫中。
                        if(!empty($_POST['TblGoods']['goods_color'])){
                            $str_color=  implode(',', $_POST['TblGoods']['goods_color']);
                            $model->goods_color=$str_color;
                        }
                        //獲取顏色陣列後將陣列轉換成字串,用豆號分隔。並儲存到資料庫中。
                        if(!empty($_POST['TblGoods']['goods_size'])){
                            $str_size=  implode(',', $_POST['TblGoods']['goods_size']);   
                            $model->goods_size=$str_size;
                        }

                        //實現檔案,圖片的上傳
                        $model->goods_small_pic=  CUploadedFile::getInstance($model, goods_small_pic);
                        $model->goods_big_pic=  CUploadedFile::getInstance($model, goods_big_pic);
                        if($model->goods_small_pic){
                            $newimg='goods_small_pic_'.time().'_'.rand(1,9999).".".$model->goods_small_pic->extensionName;
                            //$newimg="abc.jpg";
                            $model->goods_small_pic->saveAs('assets/uploads/tblgoods/'.$newimg);
                            $model->goods_small_pic='assets/uploads/tblgoods/'.$newimg;
                        }
                        if($model->goods_big_pic){
                            $newimg2='goods_big_pic_'.time().'_'.rand(1,9999).".".$model->goods_big_pic->extensionName;
                            //$newimg2="abcd.jpg";
                            $model->goods_big_pic->saveAs('assets/uploads/tblgoods/'.$newimg2);
                            $model->goods_big_pic='assets/uploads/tblgoods/'.$newimg2;
                        }
                        
			if($model->save())
				//$this->redirect(array('view','id'=>$model->goods_id));
                            $this->redirect(array('admin'));
		}

		$this->render('create',array(
			'model'=>$model,
                        //使用下拉選單,實現新增產品或修改產品時,可以從下拉列表選擇產品類別:以下為第2步
                        //在Goods控制器下create將上面得到的陣列,分配到create這個VIEW頁面。
                        'category'=>$category,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
                //yii checkBoxList 的高階使用
                //如果資料庫顏色存在顏色資料,先將資料讀取出來,轉換成陣列後,再賦值給$model->goods_color
                //這時候,在檢視那邊的checkBoxList將會顯示從資料庫中存在的值了。
                if(!empty($model->goods_color)){
                    $color=$model->goods_color;
                    $arr_color= explode(',', $color);
                    $model->goods_color=$arr_color;
                }
                //如果資料庫顏色存在尺寸資料,先將資料讀取出來,轉換成陣列後,再賦值給$model->goods_size
                //這時候,在檢視那邊的checkBoxList將會顯示從資料庫中存在的值了。
                if(!empty($model->goods_size)){
                    $size=$model->goods_size;
                    $arr_size= explode(',', $size);
                    $model->goods_size=$arr_size;
                }
                
                //使用下拉選單,實現新增產品或修改產品時,可以從下拉列表選擇產品類別:以下為第1步
                //在Goods控制器下例項化category物件,並執行SQL語句,取得所有資料。
                $category =  TblCategory::model()->findAll();

		if(isset($_POST['TblGoods']))
		{                          
			$model->attributes=$_POST['TblGoods'];
                        
                        //獲取顏色陣列後將陣列轉換成字串,用豆號分隔。並儲存到資料庫中。
                        if(!empty($_POST['TblGoods']['goods_color'])){
                            $str_color=  implode(',', $_POST['TblGoods']['goods_color']);
                            $model->goods_color=$str_color;
                        }
                        //獲取顏色陣列後將陣列轉換成字串,用豆號分隔。並儲存到資料庫中。
                        if(!empty($_POST['TblGoods']['goods_size'])){
                            $str_size=  implode(',', $_POST['TblGoods']['goods_size']);   
                            $model->goods_size=$str_size;
                        }
                        
                        //實現檔案,圖片的上傳
                        $model->goods_small_pic=  CUploadedFile::getInstance($model, goods_small_pic);
                        $model->goods_big_pic=  CUploadedFile::getInstance($model, goods_big_pic);
                        if($model->goods_small_pic){
                            $newimg='goods_small_pic_'.time().'_'.rand(1,9999).".".$model->goods_small_pic->extensionName;
                            //$newimg="abc.jpg";
                            $model->goods_small_pic->saveAs('assets/uploads/tblgoods/'.$newimg);
                            $model->goods_small_pic='assets/uploads/tblgoods/'.$newimg;
                        }else{
                            $model->goods_small_pic=$_POST['temp_img1'];
                        }
                        if($model->goods_big_pic){
                            $newimg2='goods_big_pic_'.time().'_'.rand(1,9999).".".$model->goods_big_pic->extensionName;
                            //$newimg2="abcd.jpg";
                            $model->goods_big_pic->saveAs('assets/uploads/tblgoods/'.$newimg2);
                            $model->goods_big_pic='assets/uploads/tblgoods/'.$newimg2;
                        }else{
                            $model->goods_big_pic=$_POST['temp_img2'];
                        }
                        
			if($model->save())
				//$this->redirect(array('view','id'=>$model->goods_id));
                            $this->redirect(array('admin','id'=>'$model->goods_id'));
		}

		$this->render('update',array(
			'model'=>$model,
                        //使用下拉選單,實現新增產品或修改產品時,可以從下拉列表選擇產品類別:以下為第2步
                        //在Goods控制器下create將上面得到的陣列,分配到create這個VIEW頁面。
                        'category'=>$category
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('TblGoods');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new TblGoods('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['TblGoods']))
			$model->attributes=$_GET['TblGoods'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return TblGoods the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=TblGoods::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
        
        public function actionForlistbox(){
                $model=  SpecInfo::model()->findAllByAttributes(array('spec_id'=>2));
                $arr=array();
                foreach($model as $item){
                    $arr[]=$item->attributes['group'];
                }
            $js= json_encode($arr);
            echo $js;
        }

        /**
	 * Performs the AJAX validation.
	 * @param TblGoods $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='tbl-goods-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}


_form.php

<?php
/* @var $this TblGoodsController */
/* @var $model TblGoods */
/* @var $form CActiveForm */
?>
<!--以下3個檔案匯入是用於thickbox JQuery彈出視窗的-->
<link href="<?php echo CSS_URL;?>thickbox.css" rel="stylesheet" type="text/css">
<script src="<?php echo JS_URL;?>jquery-1.1.3.1.pack.js" type="text/javascript"></script>
<script src="<?php echo JS_URL;?>thickbox-compressed.js" type="text/javascript"></script>


<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'tbl-goods-form',
	// Please note: When you enable ajax validation, make sure the corresponding
	// controller action is handling ajax validation correctly.
	// There is a call to performAjaxValidation() commented in generated controller code.
	// See class documentation of CActiveForm for details on this.
	
    'enableClientValidation' => true,
    //'enableAjaxValidation'=>true,
        //要實現圖片的上傳與修改,enctype這句話一定要加上去。
        'htmlOptions'=>array('enctype'=>'multipart/form-data')
)); ?>

	<p class="note">注:帶 <span class="required">*</span> 號為必填項!</p>

	<?php echo $form->errorSummary($model); ?>

	<div class="row">
		<?php echo $form->labelEx($model,'cat_id'); ?>
                <!--
                //使用下拉選單,實現新增產品或修改產品時,可以從下拉列表選擇產品類別:以下為第5步
                //在_form這個VIEW頁面中,使用CHtml::listDate方面,將分類資訊語取出來。
                //$model:這個表示goods的model物件
                //cat_id:這個表示表單中提交出去的name
                //$category:這個表示從Goods模型中關聯到的Category的模型資料
                //cat_id:這個表示下拉選單使用的值
                //cat_name:這個表示form中顯示出來的名字,實際用到的其實是cat_id
                -->
                <?php echo $form->dropDownlist($model,'cat_id',CHtml::listData($category, 'cat_id', 'cat_name'));?>
            
		<?php echo $form->error($model,'cat_id'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'goods_sn'); ?>
		<?php echo $form->textField($model,'goods_sn',array('size'=>16,'maxlength'=>16)); ?>
		<?php echo $form->error($model,'goods_sn'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'goods_name'); ?>
		<?php echo $form->textField($model,'goods_name',array('size'=>32,'maxlength'=>32)); ?>
		<?php echo $form->error($model,'goods_name'); ?>
	</div>
        
        <div class="row">
            <?php //yii checkBoxList 的高階使用
                    //checkBoxList($model,'goods_color'...)中的goods_color如果被賦了一個數組,則checkBoxList將會顯示預設值。
                    //示例:$model->goods_color=array(1,3);
                    //則checkBoxList對應的值將會打上勾
            ?>
            
		<?php echo $form->labelEx($model,'goods_color'); ?><br/>
            
            <?php 
                $listdata=CHtml::listData(SpecInfo::model()->findAllByAttributes(array('spec_id'=>2)),'spec_info_id','spec_info_name');
            ?>
            
            <script type="text/javascript">
                var k=1;
            </script>

            <?php echo $form->checkBoxList($model,'goods_color',  
                        $listdata,
                         array(
                             'template'=>'{input} {label}',//複選框和文字的版式,這裡可以加一些HTML標籤
                             'separator'=>'
                                 <script type="text/javascript">
                                    var br="<img id=br"+window.k+" />";
                                    document.write(br);
                                    window.k++;
                                </script>',//分隔符,預設分隔符為<br/>,如果不想為<br/>,可以設定為 或其他,這裡可以加一些HTML標籤。
                             'checkAll'=>'全選',
                             'checkAllLast'=>true,
                             'labelOptions'=>array(
                                 'style'=>'display:inline; margin-right:10px;'
                                 )
                             )
                    ); 
            ?>
		<?php echo $form->error($model,'goods_color'); ?>
	</div>
        
        <script type="text/javascript">
            $(document).ready(function(){
                var i=0;
                var j=1;
                $.ajax({
                    type:'post',
                    dataType:'json',
                    url:'./index.php?r=admin/TblGoods/forlistbox',
                    success:function(msg){
                        var arr=[];
                        $.each(msg,function(index,val){
                            arr[index]=val;
                        });
                        while(i<arr.length){
                            if((arr[j]-arr[i])>0){
                                $("#br"+j).after("<br/>");
                            }
                            i++;
                            j++;
                        }
                        $("#br"+i).after("<br/>");//最後那個複選框後面加一個BR,使用者分隔後面的全選框。
                    }
                });
            });
        </script>
        
        <div class="row">
		<?php echo $form->labelEx($model,'goods_size'); ?>
            <?php echo $form->checkBoxList($model,'goods_size',  
                        CHtml::listData(SpecInfo::model()->findAllByAttributes(array('spec_id'=>3)),'spec_info_id','spec_info_name'),
                         array(
                             'separator'=>'',
                             'labelOptions'=>array(
                                 'style'=>'display:inline; margin-right:10px;'
                                 )
                             )
                    ); 
            ?>
		<?php echo $form->error($model,'goods_size'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'click_count'); ?>
		<?php echo $form->textField($model,'click_count',array('size'=>8,'maxlength'=>8)); ?>
		<?php echo $form->error($model,'click_count'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'brand_id'); ?>
		<?php echo $form->textField($model,'brand_id',array('size'=>8,'maxlength'=>8)); ?>
		<?php echo $form->error($model,'brand_id'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'goods_number'); ?>
		<?php echo $form->textField($model,'goods_number',array('size'=>8,'maxlength'=>8)); ?>
		<?php echo $form->error($model,'goods_number'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'market_price'); ?>
		<?php echo $form->textField($model,'market_price',array('size'=>8,'maxlength'=>8)); ?>
		<?php echo $form->error($model,'market_price'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'shop_price'); ?>
		<?php echo $form->textField($model,'shop_price',array('size'=>8,'maxlength'=>8)); ?>
		<?php echo $form->error($model,'shop_price'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'promote_price'); ?>
		<?php echo $form->textField($model,'promote_price',array('size'=>8,'maxlength'=>8)); ?>
		<?php echo $form->error($model,'promote_price'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'promote_start_date'); ?>
		<?php echo $form->textField($model,'promote_start_date'); ?>
		<?php echo $form->error($model,'promote_start_date'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'promote_end_date'); ?>
		<?php echo $form->textField($model,'promote_end_date'); ?>
		<?php echo $form->error($model,'promote_end_date'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'goods_desc'); ?><br/>
		<?php //echo $form->textField($model,'goods_desc',array('size'=>60,'maxlength'=>255)); ?>
                <?php
                    //這裡是使用ckeditor來輸入文字資訊
                    //使用前,先解壓ckeditor,然後複製到extensions
                    //呼叫時:application.extensions.ckeditor.CKEditor相當於application.extensions.ckeditor.CKEditor.php
                    $this->widget('application.extensions.ckeditor.CKEditor', array(
                    'model'=>$model,//$model表示資料表的model
                    'attribute'=>'goods_desc',//表示要操作的欄位
                    'language'=>'zh-cn',
                    ));
                ?>
                <?php echo $form->error($model,'goods_desc'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'goods_small_pic'); ?>
		<?php //echo $form->textField($model,'goods_small_pic',array('size'=>60,'maxlength'=>255)); ?>
		<?php echo CHtml::activeFileField($model,'goods_small_pic'); ?>
                <?php echo $form->error($model,'goods_small_pic'); ?><br/>
                <!--預覽圖,並且設定一個隱藏域,用來暫存修改前的URL資訊-->
                <?php echo '<img src="'.$model->goods_small_pic.'"    width="100px"/>'; ?>
                <?php if(!$model->isNewRecord){?>
                <input type="hidden" name="temp_img1" id="hiddenField"    value="<?php echo $model->goods_small_pic;?>"/>
                <?php }?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'goods_big_pic'); ?>
		<?php //echo $form->textField($model,'goods_big_pic',array('size'=>60,'maxlength'=>255)); ?>
		<?php echo CHtml::activeFileField($model,'goods_big_pic'); ?>
                <?php echo $form->error($model,'goods_big_pic'); ?><br/>
                <!--預覽圖,並且設定一個隱藏域,用來暫存修改前的URL資訊-->
                <?php echo '<img src="'.$model->goods_big_pic.'"    width="100px"/>'; ?>
                <?php if(!$model->isNewRecord){?>
                <input type="hidden" name="temp_img2" id="hiddenField"    value="<?php echo $model->goods_big_pic;?>"/>
                <?php }?>

	</div>
        
        

	<div class="row">
		<?php echo $form->labelEx($model,'is_sale'); ?>
		<?php echo $form->textField($model,'is_sale'); ?>
		<?php echo $form->error($model,'is_sale'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'is_delete'); ?>
		<?php echo $form->textField($model,'is_delete'); ?>
		<?php echo $form->error($model,'is_delete'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'is_best'); ?>
		<?php echo $form->textField($model,'is_best'); ?>
		<?php echo $form->error($model,'is_best'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'is_new'); ?>
		<?php echo $form->textField($model,'is_new'); ?>
		<?php echo $form->error($model,'is_new'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'is_hot'); ?>
		<?php echo $form->textField($model,'is_hot'); ?>
		<?php echo $form->error($model,'is_hot'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'is_promote'); ?>
		<?php echo $form->textField($model,'is_promote'); ?>
		<?php echo $form->error($model,'is_promote'); ?>
	</div>

	<div class="row">
		<?php echo $form->labelEx($model,'add_time'); ?>
		<?php echo $form->textField($model,'add_time'); ?>
		<?php echo $form->error($model,'add_time'); ?>
	</div>
        <div class="row">
		<?php echo $form->labelEx($model,'shops_id'); ?>
		<?php //echo $form->textField($model,'shops_id'); ?>
            <?php echo $form->dropDownList($model,'shops_id',  CHtml::listData(TblShops::model()->findAll(),'shops_id','shops_name')) ?>
		<?php echo $form->error($model,'shops_id'); ?>
	</div>
        


	<div class="row buttons">
		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
	</div>

<?php $this->endWidget(); ?>

</div><!-- form -->