如何在Yii中使用JSON

时间:2014-10-02 21:41:10

标签: php ajax json yii

我想向控制器动作发送/获取变量。我的代码:

查看文件

....
<button id="radiyo">radio</button>
<script>
$("#radiyo").on("click", function(){
    var $radio = $('input[type=radio][name=siniflerin-siyahisi]:checked').attr('id');
    $.ajax({
        type: 'POST',
        url: '<?=Yii::app()->baseUrl;?>/ideyalar/sech/radio',
        async: false,
        cache: false,
        data: {radio: $radio},
//        datatype: "html",
        success:function(){

            alert($radio);
        }
    });
    $.ajax({
        type: 'GET',
        url: '<?=Yii::app()->baseUrl;?>/ideyalar/sech/radio',
        async: false,
        cache: false,
        datatype: "json",
        data: {change: $sql},
        success: function(data) {
            alert(data.change);
        }
    });
});
</script>
....

控制器操作

public function actionSech ($radio)
{
    $sql = Yii::app()->db->createCommand()
        ->select ('m.maraq')
        ->from ('maraq m')
        ->where ('m.idsinif=:ids', [':ids'=>$radio])
        ->queryAll();
    $gonderilen = CJSON::encode(['change'=>$sql]);
}

我从Yii官方网站和其他论坛上阅读文章。但我无法理解我该怎么做。

请告诉我,如何将$sql变量发送到查看文件

感谢。

1 个答案:

答案 0 :(得分:0)

我不太确定你想要什么。但是,我想指出一些片段。

在视图文件

<?php
    Yii::app()->clientScript->registerScript("header-info","
        var baseUrl = '".Yii::app()->baseUrl;."';  
    ",CClientScript::POS_HEAD);
?>

<button id="radiyo">radio</button>
<script>
    $("#radiyo").on("click", function(){
    var radioValue = $('input[type=radio][name=siniflerin-siyahisi]:checked').attr('id');
    $.ajax({
        url: baseUrl +'/ideyalar/sech',
        dataType:'json',
        type:'POST',        
        data:{radioValue:radioValue},
        async:false
        }).done(function(data){
         if(data['status'] == 'OK'){
             alert(data['returnValue']);
         }else if(data['status'] == 'ERROR'){
             alert("HERE WE GO ERROR");
         }
     });
   });
</script>

您的控制器操作;

public function actionSech()
{
   //In my point, I never call db layer in controller. Controller should be routing purpose

   If(Yii::app()->request->isAjaxRequest){
      $radioValue = isset($_REQUEST['radioValue']) ? $_REQUEST['radioValue'] : "";
      $returnObj = array();
      if($radioValue !=""){
         $query = "SELECT `maraq` FROM maraq WHERE idsinif='$radionValue'";
         $result = Yii::app()->db->createCommand($query)->queryScalar();
         if($result != "" || $result != null){  //ensure result is correct or not
             $returnObj['returnValue'] = $result;
             $returnObj['status'] = 'OK'; 
         }else{
             $returnObj['status'] = 'ERROR'; 
         } 
      }else{   //if radiovalue is blank string
         $returnObj['status'] = 'ERROR';
      }
      echo json_encode($returnObj);
   }
}

希望这有帮助!顺便说一句,JavaScript变量不能用 $ 初始化。只是 var yourVar =“”;