JSON不能与CodeIgniter和AJAX一起使用

时间:2016-02-05 07:04:59

标签: json ajax twitter-bootstrap codeigniter

大家好日子。

对不起,如果我问这个问题在我的开发中阻止了我。我只是jquery和json中的新手,它还不知道如何操纵数据。对不起。

作为背景,这是我的VIEW,因为我正在使用CodeIgniter框架。此搜索按钮(黄色)不是Boostrap Datatable的默认“搜索”。因为,作为我的设计,我将首先搜索员工的姓氏然后点击搜索按钮。如果有要检索的记录,那么我将在数据表中添加/显示它。

enter image description here

所以这是我的代码:

查看:

<div class="panel-body">
    <div class="col-sm-3 col-md-3 pull-right">
        <form class="navbar-form" role="search">
            <div class="input-group">
                <input type="text" class="form-control" placeholder="Search" name="search_empname" id="search_empname" autocomplete="off">                                  

                <div class="input-group-btn">
                    <button class="btn btn-default" type="button" id="btnsearch">
                    <i class="glyphicon glyphicon-search"></i></button>                                     
                </div>                                  
            </div>
        </form>
    </div>

    <div class="table-responsive">
        <table class="table table-striped table-bordered table-hover" id="employee_access_dataTables">
            <thead>
                <tr>
                    <th width="10%">Employee No.</th>
                    <th width="10%">Username</th>
                    <th width="10%">FirstName</th>
                    <th width="10%">MiddleName</th>
                    <th width="10%">LastName</th>                                       
                    <th width="10%">Prim. Role</th>
                    <th width="10%">Sec. Role</th>
                    <th width="10%">Email</th>
                    <th width="10%">Status</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>                         
            </tbody>
        </table>
    </div>

CONTROLLER

public function search_employee() {
    $search_empname = trim($this -> security -> xss_clean($this -> input -> get('lastname')));
    $data['empresult'] = $this -> msystems_admin -> search_employee($search_empname);
    echo json_encode($data);
}

AJAX

$('#btnsearch').click(function(){
    var gv_lname = $('#search_empname').val();

    if(gv_lname != ''){
        $.ajax({
            type:'GET',
            cache: false,
            datatype: 'json',
            url:'<?php echo site_url('csystems/search_employee');?>',
            data:'lastname='+gv_lname,
            success: function(data){
                console.log(data);  
                //I am not sure what to place here          
            }   
        });
    }               
});

请您告诉我如何获得我想要的输出?非常感谢你。

注意:即使我做了ALERT,也无法显示JSON的输出。 :(

更新: 这是Chrome开发人员工具的网络标签。 enter image description here

当我点击URL search_employee时,我什么都没有预览。 enter image description here

enter image description here

更新2: 如果我改变了我的控制器,我不会像JSON一样传递它。

public function search_employee() {
    $search_empname     = trim($this -> security -> xss_clean($this -> input -> get('lastname')));
    $data['empresult']  = $this -> msystems_admin -> search_employee($search_empname);
    //echo json_encode($data);

    foreach ($data['empresult'] as $row){
        $output  = $row -> fname;
        $output .= $row -> mname;
        $output .= $row -> lname;
    }

    echo $output;       

}

在我的AJAX中,我删除了JSON作为数据类型,如下面这个,

$('#btnsearch').click(function(){
    var gv_lname = $('#search_empname').val();

    if(gv_lname != ''){
        $.ajax({
            type:'GET',
            cache: false,
            //dataType: 'json',
            url:'<?php echo site_url('csystems/search_employee');?>',
            data:'lastname='+gv_lname,
            success: function(data){
                console.log(data);  
                //I am not sure what to place here                          
            }   
        });
    }               

});

然后我从控制台日志中看到了响应。请看截图。 enter image description here

我不确定JSON有什么问题...... :(

3 个答案:

答案 0 :(得分:1)

使用

dataType: 'json',   instead of datatype: 'json',

T应该是资本。 希望它有效

答案 1 :(得分:0)

首先,感谢@Gwendal和@Praveen指导我解决这个问题。我在使用JSON时发现了实际的错误。

在我的控制器中使用此代码,

var_dump(json_encode($data));
var_dump( json_last_error());

使用上面的代码,它将在控制台日志中返回响应。 它的反应如下:

bool(false)
int(5)

现在,查看发现here的PHP手册,此错误 int(5)与以下内容有关:

0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8

现在,我将查看JSON_ERROR_UTF_8的原因。

感谢你们所有人。

更新此错误JSON_ERROR_UTF_8

出现此错误的原因是,无法从SQL检索返回的数组中创建JSON格式。这是因为附加到对象的Resouce ID。当您执行 print_r 命令时,您无法看到资源ID。但是如果你做一个var_dump,那么你会注意到没有。

这里是两种方法的截图:

使用PRINT_R:看不到资源ID。

enter image description here

使用VAR_DUMP:显示资源ID enter image description here

因此,从这两个屏幕截图中,我得出结论,返回的SQL记录具有每条记录的资源ID。因此,当我使用JSON_ENCODE函数对其进行编码时,由于无法解释的资源ID,它会失败。

要解决此问题,我首先将生成的SQL结果转换为关联数组,然后将该数组传递给函数JSON_ENCODE。使用此方法,它将提供JSON响应。

所以在我的模型中,我调整了这个方式:

public function search($q) {        
    $sql = "SELECT statment here";
    $query = $this -> db -> query($sql);        
    if ($query -> num_rows() > 0) {
        $ctr = 0;
        foreach($query->result() as $row) {
            //make an associative array
            $data[$ctr]['fname'] = $row->fname;
            $data[$ctr]['mname'] = $row->mname;
            $data[$ctr]['lname'] = $row->lname;

            $ctr++;

            //list all the other fields here
        }
        return $data;
    }
    return false;
}

然后在我的CONTROLLER中,我现在可以将此数组传递给JSON_ENCODE函数。所以,

public function search_employee() {
    $search_empname = trim($this -> security -> xss_clean($this -> input -> get('lastname')));
    $data = $this -> msystems_admin -> search_employee($search_empname);
    echo json_encode($data)     
}

因此,当我运行前端搜索时,现在有一个通过AJAX调用的响应。 enter image description here

再次,百万感谢所有评论的人。我找到了调试此问题的正确方向。我希望这也有助于像我这样的其他新手。奖励。

答案 2 :(得分:0)

您的回复标题为Content-Type: text/html。尝试在您的回复中发送正确的json标头。在echo之前将此行添加到您的php:

header('Content-Type: application/json');

另请参阅:jQuery AJAX Call to PHP Script with JSON Return