如何使用json_encode将数据从Controller传输到我的View?

时间:2015-07-31 08:47:32

标签: php json

我试图从我的控制器获取数据并将其访问到我的视图中。我想在将数据发送到View时尝试对数据进行编码。这就是我到目前为止所做的事情。

Controller.php这样

if($survey = $this->survey->get($survey_id, $user, $page_no, $items_per_page)) {
   echo json_encode(array("survey" => $survey, "status_message" => "Survey has been fetched", "status" => true, "status_code" => 2));
   }

我想将$survey数据传递给我的视图,以便我可以访问它的元素。

model.php

function get($survey_id, $user, $page_no, $items_per_page) {

    .
    .
    .
    .
     $questions = $this->get_questions(null, $survey_id, $page_no, $items_per_page);
     $num_of_questions = $this->get_question_number(null, $survey_id);
     $total_page = ceil($num_of_questions/$items_per_page);

     $survey['items'] = $questions;
     $survey['total_page'] = $total_page;
     $survey['page_group'] = $page_no;
     $survey['survey_id'] = $survey_id;
    .
    .
    .
    .
}

现在在我的view.php中,我想要类似的东西:

view.php

<script type="text/javascript">
 var survey_id = json_decode(survey[survey_id]);
 .
 .
 .
</script>

1 个答案:

答案 0 :(得分:0)

你不需要json_encode。您可以将直接数组用于视图。

Controller.php这样

$data['survey']="";
if($survey = $this->survey->get($survey_id, $user, $page_no, $items_per_page)) {
    $data['survey']=$servey;
}
$this->load->view('your_view_name',$data);

View.php

print_r($survey);