如何在codeigniter中使用ajax加载页面的一部分

时间:2015-02-25 19:41:19

标签: jquery ajax codeigniter

位指示:

public function index()
{   

            //Get all data from database
    $data['products'] = $this->billing_model->get_all();
            //send all product data to "shopping_view", which fetch from database.      
    $this->load->view('shopping_view', $data);
}

      function give_more_data() 
  {
    if (isset($_POST['category'])) {
      $data['ajax_req'] = TRUE;
      $data['node_list'] = $this->billing_model-get_node_by_type($_POST['category']);
      $this->load->view('shopping_view',$data);
    }

查看:

<?php 
if (!isset($ajax_req)): ?>
<div class="show-veg"><p>View only veg</p></div>
<div class="show-drinks"><p>View only drinks</div>
      <?php endif; ?>
<div id="ajax-content-container">

    <?php foreach ($node_list as $key=>$value): 


                $id = $value['serial'];
                $name = $value['name'];
                $description = $value['description'];
                $price = $value['price'];
                ?>

                <div id='product_div'>  
                    <div id='image_div'>
                        <img src="<?php echo base_url() . $product['picture'] ?>"/>
                    </div>


                  <div id='info_product'>
                        <div id='name'><?php echo $name; ?></div>
                        <div id='desc'>  <?php echo $description; ?></div>
                        <div id='rs'><b>Price</b>:<big style="color: #E00">
                            Ksh <?php echo $price; ?></big></div>
                        <?php

                        // Create form and send values in 'shopping/add' function.
                        echo form_open('shopping/add');
                        echo form_hidden('id', $id);
                        echo form_hidden('name', $name);
                        echo form_hidden('price', $price);
                        ?> </div> 
                    <div id='add_button'>
                        <?php
                        $btn = array(
                            'class' => 'fg-button teal',
                            'value' => 'Add to Bill',
                            'name' => 'action'
                        );

                        // Submit Button.
                        echo form_submit($btn);
                        echo form_close();
                        ?>
                    </div>
                </div>

      <?php endforeach; ?>

JAVASCRIPT:

<script type="text/javascript">
$(document).ready(function () {
  ajax_vegmeals();
  ajax_nonvegmeals();
  ajax_salads();
   ajax_drinks();
});

function ajax_vegmeals() {
  $('.show-veg').click(function () {
    $.ajax({
      url: base_url+"index.php?/shopping/give_more_data",
      async: false,
      type: "POST",
      data: "type=vegmeal",
      dataType: "html",
      success: function(data) {
        $('#ajax-content-container').html(data);
      }
    })
  });

}

function ajax_nonvegmeals() {
  $('.show-nonveg').click(function () {
    $.ajax({
      url: base_url+"index.php?/shopping/give_more_data",
      async: false,
      type: "POST",
      data: "type=nonvegmeal",
      dataType: "html",
      success: function(data) {
        $('#ajax-content-container').fadeIn().html(data);
      }
    })
  });
}

function ajax_salads() {
  $('.show-salads').click(function () {
    $.ajax({
      url: base_url+"index.php?/shopping/give_more_data",
      async: false,
      type: "POST",
      data: "type=salads",
      dataType: "html",
      success: function(data) {
        $('#ajax-content-container').fadeIn().html(data);
      }
    })
  });
}

我看到了关于ajax的教程,我想用它来根据所选的类别在页面上加载产品,例如,如果你选择饮料,页面加载饮料而不加载页面。我尝试编辑代码但没有成功。我得到一个错误。

请帮帮忙?

2 个答案:

答案 0 :(得分:0)

您的控制器需要将加载的视图分配给第三个参数设置为TRUE的变量,然后您可以将其传递给您的ajax结果。像这样:

$view = $this->load->view('shopping_view',$data, TRUE);
echo $view;

更新:好的,我现在理解你的问题了......首先,试图理解你想要做什么是令人困惑的,谢谢你在更新中清理它。问题是您在视图顶部加载视图,并且尝试以错误的方式组合技术。您首先在PHP中解析数组,然后您想使用PHP解析来自AJAX的结果,这种结构将无法工作。如果你想使用AJAX,我会在JS中留下迭代和解析。我会做以下事情:

在您的控制器中,将这些功能分开:

function index() {//This will load your HTML, and JS
    $this->load->view('shopping_view');
}

function give_more_data() { //this will return data to AJAX
    $postdata = $this->input->postdata();
    if (isset($postdata['type'])) {
       $results = $this->billing_model->get_node_by_type($postdata['type']);
    } else {
       $results = $this->billing_model->get_all();
    }
    echo json_encode($results);
}

现在,在你的HTML中:

<a data-type="veg" class="filter">View only veg</a>
<a data-type="drinks" class="filter">View only drinks</a>
<a data-type="meat" class="filter">View only meat</a>
<div id="ajax-content-container"></div>

你的JS:

<script>
  function filter(type) {
    $.ajax({
      url: base_url + "index.php?/shopping/give_more_data",
      async: false,
      type: "POST",
      data: "type=" + type,
      dataType: "html",
      success: function(data) {
        var results = JSON.parse(data);
        $.each(results, function(key, value) {
          var list = "<ul>";  //As an example, im creating a list, but you can do as you wish
          list += "<li>" + value.serial + "</li>";
          list += "<li>" + value.name + "</li>";
          list += "<li>" + value.description + "</li>";
          var list = "</ul>";
          $('#ajax-content-container').append(data);
        });
        $('#ajax-content-container').fadeIn();
      }
    });
  }

  filter("all"); //this will be run automatically at load


  $('.filter').click(function(e) {
    e.preventDefault();
    var type = $(this).data("type");
    filter(type);
  });
</script>

答案 1 :(得分:0)

另一种方法是使用Codeigniter的视图作为模板:

模特:

class Billing_model extends CI_Model {

    function get_all() {
        $this->db->select("*");
        $this->db->from('products');
        $query = $this->db->get();
        return $query->result();
    }

    function get_node_by_type($type) {
        $this->db->select("*");
        $this->db->from('products');
        $this->db->where('type', $type);
        $query = $this->db->get();
        return $query->result();
    }

}

控制器:

class Shopping extends CI_Controller {

    function index() {
        $this->load->view('shopping_view');
    }

    function give_more_data() {
        $this->load->model('billing_model');
        $type = $this->input->post('type');
        if ($type === "All") {
            $results = $this->billing_model->get_all();
        } else {
            $results = $this->billing_model->get_node_by_type($type);
        }
        $data['node_list'] = $results;
        $filter_view = $this->load->view('templates/filter_products', $data, TRUE);

        echo json_encode($filter_view);
    }

}

VIEW(filter_products):

<?php foreach ($node_list as $key => $product) { ?>
    <div id='product_div'>  
        <div id='image_div'>
            <img src="<?= base_url() . $product->picture ?>"/>
        </div>

        <div id='info_product'>
            <div id='name'><?= $product->name ?></div>
            <div id='desc'>  <?= $product->description ?></div>
            <div id='rs'>
                <b>Price</b>:<big style="color: #E00">Ksh <?= $product->price ?></big>
            </div>
            <?php
            echo form_open('shopping/add');
            echo form_hidden('id', $product->id);
            echo form_hidden('name', $product->name);
            echo form_hidden('price', $product->price);
            ?> 
            <div id='add_button'>
                <?php
                $btn = array(
                    'class' => 'fg-button teal',
                    'value' => 'Add to Bill',
                    'name' => 'action'
                );

                echo form_submit($btn);
                ?>
            </div>
            <?php echo form_close(); ?>
        </div> 
    </div>
<?php } ?>

查看(shopping_view):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="filters">
    <label><input type="radio" name="type" value="All" checked>All</label>
    <label><input type="radio" name="type" value="veg">Veg</label>
    <label><input type="radio" name="type" value="drinks">Drinks</label>
    <label><input type="radio" name="type" value="meat">Meat</label>
</div>

<div id="ajax-content-container">
</div>

<script>
    function filter(type) {
        var url = "index.php?/shopping/give_more_data";
        var postdata = {type: type};
        $.post(url, postdata, function(data) {
            var results = JSON.parse(data);
            $('#ajax-content-container').html(results);
        });
    }

    filter("All"); //runs at load

    $('#filters input').click(function() {
        var type = $(this).val();
        filter(type);
    });
</script>