使用Codeigniter和Ajax从数据库加载更多数据 [英] Load more data from database with Codeigniter and Ajax

查看:101
本文介绍了使用Codeigniter和Ajax从数据库加载更多数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助一个按钮从数据库加载更多的数据。我发现了例子,但太糟糕了。这是我到目前为止:

I need help with a button for loading more data from the database. I've found examples, but too bad ones. Here is what I have so far:

Ajax:

$('#revendas_conteudo .btn_carregar_mais').on('click', function(e) {
    $.ajax({
        url: '/auto/carros/load_more',
        data: {
            offset: $('#offset').val(),
            limit: $('#limit').val()
        },
        success: function(data) {
            $('#revendas_conteudo .lista_estoque').append(data);
        }
    });
});

我的Controller方法调用Model load_more

My Controller method calling the Model load_more:

public function load_more()
{
    $offset = $this->input->get('offset');
    $limit = $this->input->get('limit');

    $data['res'] = $this->Pesquisas_model->load_more($offset, $limit);
    $data['offset'] = $offset + 1;
    $data['limit'] = $limit + 1;

    echo json_encode($data);
}

Pesquisas_model :: load_more $ c>:

Pesquisas_model::load_more():

public function load_more($offset, $limit)
{
    $this->db
        ->select(
            'usuario.nome_razao_social AS nome_anunciante,' .
            'modelo.modelo AS modelo,' .
            'marca.marca AS marca,' .
            'ano_modelo.ano AS ano,' .
            'ano_modelo.valor AS valor,' .
            'ano_modelo.combustivel AS combustivel,' .
            'cambio.descricao_cambio AS descricao_cambio,' .
            'estado.uf AS uf,' .
            'cidade.nome_cidade AS nome_cidade,' .
            'carro.*'
        )
        ->join('usuario', 'usuario.id = carro.id_usuario')
        ->join('ano_modelo', 'ano_modelo.id = carro.id_ano_modelo')
        ->join('modelo', 'modelo.id = ano_modelo.id_modelo')
        ->join('marca', 'marca.id_marca = modelo.id_marca')
        ->join('cambio', 'cambio.id = carro.id_cambio')
        ->join('estado', 'estado.id = carro.id_estado')
        ->join('cidade', 'cidade.id = carro.id_cidade')
        ->order_by('marca.marca', 'ASC')
        ->limit($offset, $limit);

    $query = $this->db->get($this->table);

    if ($query) {
        $data = array();

        foreach ($query->result_array() as $row) {
            $data[] = $row;
        }

        $query->free_result();

        return $data;
    }
}

HTML:

<div class="lista_estoque">
    <?php foreach ($pesquisas as $p) { ?>
        <div class="item_estoque">
            <div class="avatar">
                <img src="/uploads/carros/destaque/<?php echo $p['imagem_destaque']; ?>"/>
            </div>
            <div class="texto_anuncio">
                <h4><?php echo $p['modelo']; ?></h4>

                <div class="detalhes">
                    <span><?php echo $p['marca'] . ' | ' . $p['combustivel'] . ' | ' . $p['cor']; ?></span>
                    <span><?php echo $p['ano']; ?></span>
                    <span><?php echo number_format($p['kilometragem'], 2) . 'km'; ?></span>
                </div>

                <span class="anunciante"><?php echo $p['nome_anunciante']; ?></span>
            </div>
            <div class="texto_anuncio_right">
                <span class="preco"><?php echo 'R$ ' . $p['preco']; ?></span>
                <a href="/comprar/detalhes/<?php echo $p['id'] ?>" class="bt_vejamais">Veja Mais</a>
            </div>
        </div>
    <?php } ?>
    <div class="carregar_mais">
        <input type="hidden" name="limit" id="limit" value="1"/>
        <input type="hidden" name="offset" id="offset" value="1"/>
        <button class="btn btn_carregar_mais" data-val="0">Mostrar mais resultados</button>
    </div>

到目前为止,发生的是一个JSON代码附加到 div 。如何将这些数据转换为HTML及其类?

So far what happens is a JSON code is appended to the end of the div. How do I make this data be converted into HTML and its classes?

推荐答案

。很遗憾,我不能标记所有的他们作为正确的答案,所以让我发布我做了什么:

Most of the answers here have led me to the solution. Sadly I can't tag all of them as the correct answer, so allow me to post what I did:

首先,这是完整的Ajax。我无法使它建议使用外部文件,因此它是这样:

First, this is the full Ajax. I could not make it work with an external file as suggested, so it is like this:

$('#revendas_conteudo .btn_carregar_mais').on('click', function(e) {
    $.ajax({
        url: '/auto/carros/load_more',
        data: {
            'offset': $('#offset').val(),
            'limit': $('#limit').val()
        },
        success: function(data) {
            var obj = JSON.parse(data);
            var i = 0;
            var max = obj.total === obj.offset;

            $('#limit').val(obj.limit);
            $('#offset').val(obj.offset);

            $.each(obj, function(k, v) {
                $('#revendas_conteudo .load_more').append(
                    '<div class="item_estoque">' +
                        '<div class="avatar">' +
                            '<img src="/uploads/carros/destaque/' + obj.res[i].imagem_destaque + '"/>' +
                        '</div>' +
                        '<div class="texto_anuncio">' +
                            '<h4>' + obj.res[i].modelo + '</h4>' +

                            '<div class="detalhes">' +
                                '<span>' + obj.res[i].marca + ' | ' + obj.res[i].combustivel + ' | ' + obj.res[i].cor + '</span>' +
                                '<span>' + obj.res[i].ano + '</span>' +
                                '<span>' + obj.res[i].kilometragem + ' km</span>' +
                            '</div>' +

                            '<span class="anunciante">' + obj.res[i].nome_anunciante + '</span>' +
                        '</div>' + 
                        '<div class="texto_anuncio_right">' + 
                            '<span class="preco"> R$ ' + obj.res[i].preco + '</span>' +
                            '<a href="/comprar/detalhes/' + obj.res[i].id + '" class="bt_vejamais">Veja Mais</a>' +
                        '</div>' + 
                    '</div>'
                ).show('slow');

                i++;

                if (max) {
                    $('#revendas_conteudo .btn_carregar_mais').css({backgroundColor: '#999'}).html('Sem mais resultados').attr('disabled', true);
                }
            });
        }
    });
});

在这里,我将每个新结果附加到 div.load_more ,并且如果 total 与当前 offset 相同,则表示它已经显示所有

In here I append every new result to the div.load_more, and if the total is identical to the current offset, it means it has already shown all the values, making the button unavailable for clicking.

这里,控制器方法:

public function load_more()
{
    $offset = $this->input->get('offset');
    $limit = $this->input->get('limit');

    $data['res'] = $this->Pesquisas_model->load_more($offset, $limit);
    $data['total'] = $this->Pesquisas_model->count_all();

    if ($data['res']) {
        $data['offset'] = $offset + 2;
        $data['limit'] = $limit;

        echo json_encode($data);
    }
}

这篇关于使用Codeigniter和Ajax从数据库加载更多数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆