如何将json数据发送到codeigniter视图

嗨,我有一个问题,基于我将如何用我的控制器返回的数据替换我的网页部分。 我有一个页面直接从我的数据库显示电影的细节,我想当用户选择一个特定的类型,然后只显示该特定类别的电影。 我已经设法从选择框中获取每个类型的名称并将其发送到控制器,我将使用它从数据库中提取数据。 在我的HTML中,我使用foreach循环来加载所有数据,我的问题是如何将它们显示回视图并操纵我的php / html代码以显示它们(实际上用新的替换现有的php / html作为ajax请求)。 我知道我必须使用json_encode()将它们作为对象发回,但我不知道如何显示它们或迭代php / html标签中的数据。

使用Javascript

$(".select__sort").change(function() { var genre = $(".select__sort").val(); $.ajax({ type: "POST", url: "http://localhost:8888/Cinema_Seat_Booking_System/movie_list_full/order_by_genre", data: {'cat':genre}, dataType:"json", cache: false, success: function (data) { } }); }); 

HTML

  
All https://stackoverflow.com/questions/36137365/how-to-send-json-data-to-codeigniter-view/ <option value="https://stackoverflow.com/questions/36137365/how-to-send-json-data-to-codeigniter-view/genre ?>" selected="selected"> https://stackoverflow.com/questions/36137365/how-to-send-json-data-to-codeigniter-view/genre ?> https://stackoverflow.com/questions/36137365/how-to-send-json-data-to-codeigniter-view/

HTML foreach循环电影数据

  https://stackoverflow.com/questions/36137365/how-to-send-json-data-to-codeigniter-view/ 
<img alt='' src=https://stackoverflow.com/questions/36137365/how-to-send-json-data-to-codeigniter-view/path ?>>
https://stackoverflow.com/questions/36137365/how-to-send-json-data-to-codeigniter-view/

调节器

  public function order_by_genre() { $this->load->model('movie_list_full_model'); $ajax_request = $this->input->post('cat'); $query_data['genres'] = $this->movie_list_full_model->get_all_genres($ajax_request); $this->load->view('templates/header'); $this->load->view('home/view_movie_list_full', $query_data); $this->load->view('templates/footer_movie_list_full'); } 

ps我希望页面更改数据而不重新加载它,这就是我用ajax尝试它的原因,但我对此相当新,我被卡住了。 有帮助吗?

您可以检查ajax使用post来获取控制器然后返回json编码

 public function order_by_genre(){ $this->load->model('movie_list_full_model'); $is_post = $this->input->server('REQUEST_METHOD') == 'POST'; if($is_post){ $ajax_request = $this->input->post('cat'); echo json_encode( $this->movie_list_full_model->get_all_genres($ajax_request)); } else { $this->load->view('templates/header'); $this->load->view('home/view_movie_list_full', $query_data); $this->load->view('templates/footer_movie_list_full'); } } 

然后在javascript中你可以使用$(this).val()它获取更改元素的值(你可以使用它很多)然后如果ajax调用在div中成功显示你的电影只需用forEach追加每部电影环

 $(".select__sort").change(function() { var genre = $(this).val(); $.ajax({ type: "POST", url: "http://localhost:8888/Cinema_Seat_Booking_System/movie_list_full/order_by_genre", data: {'cat':genre}, dataType:"json", cache: false, success: function (data) { $("#movies").html(" "); //clear everything from movie div data.forEach(function(entry) { $("#movies").append("
"+entry.movie+"
"); //just add everything here }); } }); });