将PHP变量数组传递给Javascript

时间:2014-02-17 05:05:04

标签: javascript php yii

我是Yii的新手。我在php中的变量中有一组数组值。我使用这些元素来适应使用JavaScript的自动完成。我不知道如何将这些数组值传递给JavaScript,以便它为我提供所需的结果。

我的控制器操作:

public function actionIndex()
    {

            $user = Yii::app()->db->createCommand()
    ->select('cust_name')
    ->from('mst_customers')
    ->queryAll();

       $dataProvider=new CActiveDataProvider('model_name');

                $this->render('index',array(
            'dataProvider'=>$dataProvider,


        ));

    }

我的观点:

<!--Content-->

<div id="content">
    <div style="padding: 10px;">
        <a href="<?php echo $this->createUrl('/Nimsoft/create');?>" title="Create New Host" class="btn btn-primary circle_ok" style="text-decoration: none;" >Add New Host to Customer</a>

    <div style="float:right">
                         <?php
                            echo CHtml::link('Upload Customer CSV', array('/Controller/uploadCustomers'), array(
                            'onclick'=>'return hs.htmlExpand(this, { objectType: "iframe", wrapperClassName: "full-size", align: "center" } )',
                            'class'=>'btn btn-primary',
                            'id'=>'upload_link',
                            ));
                         ?>                          
                     </div>
    </div>
    <h3><?php echo $title; ?></h3>


    <div class="innerLR">
        <div class="row-fluid">
<?php 
echo $user=$_GET['user'];
$obj=$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,

    //'afterAjaxUpdate'=>'\'changeTRColor()\'',
    //'itemView'=>'_view',
    'columns'=>array(

                array(            // display 'create_time' using an expression
                            'name'=>'name',
                                            'value'=>'$data->host_name',
                ),
                array(
                            'name'=>'serviceId',
                            'value'=>'$data->host_serviceid',
                ),

                array(
                                            'name'=>'customer',
                                            'value'=>'$data->customers->cust_name',
                ),
                array(
                                    'class'=>'CButtonColumn',
                                    'template'=>'{delete}{update}',)



),
)); 

?>

       </div>

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.9.1.js"></script>
  <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script type="text/javascript">
   $(document).ready(function () {
       $('#Search').keyup(function () {

$.fn.yiiGridView.update('id of your grid to be updated', {
        data: $(this).serialize()
    });
});
   });

  //autocomplete
  $(function() {
    var availableTags = [
        <?php echo json_encode($user);?>

      /*"ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"*/
    ];
    $( "#Search" ).autocomplete({
      source: availableTags
    });
  });
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="Search">Search Customer: </label>
  <input id="Search">
</div>


</body>
</html>

        <div class="separator bottom"></div>
    </div>
</div>
<!-- // Content END -->
<div class="clearfix"></div>
<!-- // Sidebar menu & content wrapper END -->

<div id="footer" class="hidden-print">
<?php $this->renderPartial('application.views.layouts._footer_inc');  ?>
</div>

请帮我这样做。提前谢谢。

2 个答案:

答案 0 :(得分:1)

或者您可以使用Yiis CJSON::encode()

<script>
   var myVariables = <?php echo CJSON::encode($user); ?>; // forgot to close with semicolon
</script>

答案 1 :(得分:0)

您使用json_encode()正确行事。但是,如果您拥有的数组已经是数组,请不要将其包装在另一个数组中。而不是:

var availableTags = [
    <?php echo json_encode($user);?>
];

这样做:

var availableTags = <?php echo json_encode($user); ?>;

另外,请注意,您可能已经开始接受XSS攻击,并且至少存在创建一些无效HTML的风险。只要您需要将任意数据放入HTML上下文中,就必须将其转义。而不是:

<h3><?php echo $title; ?></h3>

这样做:

<h3><?php echo htmlspecialchars($title); ?></h3>

更好的是使用模板引擎。