Codeigniter AJAX的正确方法从MySQL数据库获取数据而无需刷新

时间:2015-03-27 14:03:42

标签: php jquery mysql codeigniter

我目前正在尝试使用AJAX和jQuery来完成一些基本任务而无需离开网页。我的目标是查询数据库上的表,并将该信息附加到列表而不刷新页面。

 <button class="button radius" id="btnList">Current Items</button>

这是我的按钮,其中包含ID。 (“触发按钮”);

我的脚本看起来像这样

$('#btnList').click(function(e){
    $.ajax({
        url:"<?php echo base_url();?>/cashbook/get_item",
        datatype:'json',
        type:"POST",
        success: function(result){
            alert(result);
            $.each(result.results,function(item){
                $('ul').append('<li>' + item + '</li>')
            })
        }
    })
    $('#div_list').toggle(900)
})

我的目标是当点击按钮时,它会触发并发挥其魔力并返回数据并将其附加到列表中,该列表在完成后打开包含列表的Div。问题是我收到错误“TypeError:undefined不是对象(评估'a.length')” 我的控制器

function get_item()

{
    $data = $this -> M_cashbook -> cashbook_items();

    echo json_encode($data);

}

我不确定我在控制器中做了什么是正确的,但当它设置为echo或print时,它会返回jSon字符串并在警报中标记,但也会在屏幕顶部显示为文本,如果更改要返回json_encode,警报显示为空白,没有Json无效。

我做错了吗?如果,那么实现我想做的事情的正确方法是什么。

由于

更新:

function cashbook_items()
{
    $this -> db -> select('name');
    $this -> db -> from('items');
    $query = $this -> db ->get();

    return $query -> result();
}

这是我的模特

这是我的2个控制器函数,第一个是调用第二个获取内容的页面的默认加载,第二个是调用数据库并返回数据的繁琐工作

function items()
{

    $data['items'] = $this ->get_item();
    $this->load->view('/holders/header');
    $this->load->view('/cash/v_cashbook_items_page',$data);
    $this->load->view('/holders/footer');
}

function get_item()

{
    $data = $this -> M_cashbook -> cashbook_items();

    echo json_encode($data);

}

最后是视图

    <style>
    ul {
        list-style-type: none;
    }
</style>
<div align="center" style="padding-top: 1%" id="div_main">
    <div class="jumbotron">
        <h1>Cashbook Items</h1>

        <p>Add items to to cashbook so they used <br>when adding incomings and out goings later</p>

        <form id="items_form" data-abide>
            <div class="large-3 large-centered columns">
                <label>New Item Name
                    <input type="text" required name="item" id="item_name">
                </label>
                <small class="error">No item added</small>
            </div>

            <button class="button radius" id="btnItem">Submit</button>
        </form>
        <a href="#" data-reveal-id="firstModal" class="radius button" id="btnList">Item List</a>
    </div>

</div>

<div class="row">
    <div id="firstModal" class="reveal-modal" data-reveal align="center">
        <h3>Current Items</h3>

        <p>Reccuring Items in the database</p>
        <ul id="list_item">
        </ul>
    </div>
</div>
</div>
<br>

<script>

    $('#btnList').click(function (e) {
        $.ajax({
            url: "<?php echo base_url();?>/cashbook/get_item",
            dataType: 'text',
            type: "POST",
            success: function (result) {
                var obj = $.parseJSON(result);
                $.each(obj, function (index, object) {
                    $('#list_item').append('<li>' + object['name'] + '</li>');
                })
            }
        })
    })

    $('#items_form').submit(function (e) {
        e.preventDefault();
        var data = $('#item_name').val();
        alert(data);
        $.ajax({
            url: "<?php echo base_url();?>/cashbook/new_item",
            type: 'POST',
            data: "item=" + data,
            success: function () {
                alert('THIS WORKED');

            },
            error: function () {
                alert('Nah died');
            }

        });
    })
</script>

1 个答案:

答案 0 :(得分:3)

你可以使用result_array();如果要检索多行。它将返回纯数组。

function cashbook_items()
{
    $this -> db -> select('name');
    $this -> db -> from('items');
    $query = $this -> db ->get();

    return $query -> result_array();
}

然后在你看来:

$('#btnList').click(function(e){
    $.ajax({
        url:"<?php echo base_url();?>/cashbook/get_item",
        dataType:'text',
        type:"POST",
        success: function(result){
            var obj = $.parseJSON(result);
            console.log(obj);
           // $.each(result.results,function(item){
           //     $('ul').append('<li>' + item + '</li>')
           // })
        }
    })
    $('#div_list').toggle(900)
})

您可以使用console.log(obj);

查看obj返回的内容
$.parseJSON(result); will result in the conversion of the encoded json to an array of object.

如果要访问Parsed JSON,请使用ff。

obj[0]

这表示您将返回查询的第一行。

obj[0]['name'];

要访问各个列,您可以使用该列的名称。您在模型中说明了这一点。

$('#btnList').click(function(e){
    $.ajax({
        url:"<?php echo base_url();?>/cashbook/get_item",
        dataType:'text',
        type:"POST",
        success: function(result){
            var obj = $.parseJSON(result);
            $.each(obj,function(index,object){
                $('ul').append('<li>' +object['name']+ '</li>');
            })
        }
    })
    $('#div_list').toggle(900)
})

编辑:

在你的视图中。

  <style>
    ul {
        list-style-type: none;
    }
</style>
<div align="center" style="padding-top: 1%" id="div_main">
    <div class="jumbotron">
        <h1>Cashbook Items</h1>

        <p>Add items to to cashbook so they used <br>when adding incomings and out goings later</p>

        <form id="items_form" data-abide>
            <div class="large-3 large-centered columns">
                <label>New Item Name
                    <input type="text" required name="item" id="item_name">
                </label>
                <small class="error">No item added</small>
            </div>

            <button class="button radius" id="btnItem">Submit</button>
        </form>
        <a href="#" data-reveal-id="firstModal" class="radius button" id="btnList">Item List</a>
    </div>

</div>

<div class="row">
    <div id="firstModal" class="reveal-modal" data-reveal align="center">
        <h3>Current Items</h3>

        <p>Reccuring Items in the database</p>
        <ul id="list_item">
        </ul>
    </div>
</div>
</div>
<br>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script> 
<!--dont forget to add your jquery if you are using jquery functions and methods! -->
<script>
$(document).ready(function(){ //remember to put document.ready function when you are using jquery then insert your jquery functions inside.
    $('#btnList').on('click',function (){
        $.ajax({
            url: "<?php echo base_url();?>index.php/cashbook/get_item",
            dataType: 'text',
            type: "POST",
            success: function (result) {
                var obj = $.parseJSON(result);
                $.each(obj,function(index, object) {
                    $('#list_item').append('<li>' + object['name'] + '</li>');
                });
            }
        })
    });


    $('#items_form').submit(function (e) {
        e.preventDefault();
        var yourItem = $('#item_name').val();
        $.ajax({
            url: "<?php echo base_url();?>/cashbook/new_item",
            type: 'POST',
            data: {data:yourItem},
            success: function (data) {
                alert('THIS WORKED');

            },
            error: function () {
                alert('Nah died');
            }

        })
    });

});
</script>

你的控制器:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class cashbook extends CI_Controller{
    function __construct() {
        parent::__construct();
            $this->load->helper('url');
            $this->load->database();
            $this->load->model('M_cashbook');
    }

    function index(){
        $this->load->view('load_your_view_here'); //load your view here if you are using index as your default action when loading the default controller.
    }

    function items(){
        $data['items'] = $this ->get_item();
        $this->load->view('/holders/header');
        $this->load->view('/cash/v_cashbook_items_page',$data);
        $this->load->view('/holders/footer');
    }

    function get_item(){
        $data = $this->input->post('data');
        $data = $this -> M_cashbook -> cashbook_items();
        echo json_encode($data);
    }
}